Date picker from SwipeStackAdapter adapter - java

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

Related

listview won't populate from other class

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.

Toast On ArrayAdapter

Toast On ArrayAdapter
How to Show Toast message On QuoteArrayAdapter OnClick textViewQuoteLike
Show message Like is Done
public static ViewHolder create(RelativeLayout rootView) {
ImageView imageViewProfilePhoto = (ImageView) rootView.findViewById(R.id.imageViewProfilePhoto);
TextView textViewQuoteContent = (TextView) rootView.findViewById(R.id.textViewQuoteContent);
TextView textViewProfileName = (TextView) rootView.findViewById(R.id.textViewProfileName);
final TextView textViewQuoteLike = (TextView) rootView.findViewById(R.id.textViewQuoteLike);
TextView textViewQuoteCopy = (TextView) rootView.findViewById(R.id.textViewQuoteCopy);
TextView textViewQuoteShare = (TextView) rootView.findViewById(R.id.textViewQuoteShare);
final TextView textViewQuoteId = (TextView) rootView.findViewById(R.id.textViewQuoteId);
textViewQuoteLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new GetDataLike().execute(textViewQuoteId.getText().toString());
String currentLike = textViewQuoteLike.getText().toString();
currentLike = currentLike.replace("پسندیدم (","");;
currentLike = currentLike.replace(")","");;
int newLike = Integer.valueOf(currentLike.toString()) + 1;
textViewQuoteLike.setText("پسندیدم ("+newLike+")");
/*Toast.makeText(Need Activity, "Like is done.",
Toast.LENGTH_LONG).show();*/
}
});
return new ViewHolder(rootView, imageViewProfilePhoto, textViewQuoteContent, textViewProfileName, textViewQuoteLike, textViewQuoteCopy, textViewQuoteShare, textViewQuoteId);
}
If there is a way that in HomeFragment Put it, Please give an example
QuoteArrayAdapter.java
package com.example.adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.example.R;
import com.example.model.QuoteDataModel;
import com.example.parser.JSONParser;
import com.example.utils.Keys;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Transformation;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
public class QuoteArrayAdapter extends ArrayAdapter<QuoteDataModel> {
List<QuoteDataModel> modelList;
Context context;
private LayoutInflater mInflater;
// Constructors
public QuoteArrayAdapter(Context context, List<QuoteDataModel> objects) {
super(context, 0, objects);
this.context = context;
this.mInflater = LayoutInflater.from(context);
modelList = objects;
}
#Override
public QuoteDataModel 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.quote_row, parent, false);
vh = ViewHolder.create((RelativeLayout) view);
view.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
QuoteDataModel item = getItem(position);
vh.textViewQuoteContent.setText(item.getQuoteContent());
vh.textViewProfileName.setText(item.getProfileName());
vh.textViewQuoteLike.setText("پسندیدم ("+item.getQuoteLike()+")");
vh.textViewQuoteCopy.setText("کپی کردن");
vh.textViewQuoteShare.setText("اشتراک گزاری");
vh.textViewQuoteId.setText(item.getQuoteId());
Picasso.with(context).load(item.getProfilePhoto()).placeholder(R.drawable.empty_profile_photo).error(R.drawable.empty_profile_photo).transform(new CircleTransform()).into(vh.imageViewProfilePhoto);
return vh.rootView;
}
private static class ViewHolder {
public final RelativeLayout rootView;
public final ImageView imageViewProfilePhoto;
public final TextView textViewQuoteContent;
public final TextView textViewProfileName;
public final TextView textViewQuoteLike;
public final TextView textViewQuoteCopy;
public final TextView textViewQuoteShare;
public final TextView textViewQuoteId;
private ViewHolder(RelativeLayout rootView, ImageView imageViewProfilePhoto, TextView textViewQuoteContent, TextView textViewProfileName, TextView textViewQuoteLike, TextView textViewQuoteCopy, TextView textViewQuoteShare, TextView textViewQuoteId) {
this.rootView = rootView;
this.imageViewProfilePhoto = imageViewProfilePhoto;
this.textViewQuoteContent = textViewQuoteContent;
this.textViewProfileName = textViewProfileName;
this.textViewQuoteLike = textViewQuoteLike;
this.textViewQuoteCopy = textViewQuoteCopy;
this.textViewQuoteShare = textViewQuoteShare;
this.textViewQuoteId = textViewQuoteId;
}
public static ViewHolder create(RelativeLayout rootView) {
ImageView imageViewProfilePhoto = (ImageView) rootView.findViewById(R.id.imageViewProfilePhoto);
TextView textViewQuoteContent = (TextView) rootView.findViewById(R.id.textViewQuoteContent);
TextView textViewProfileName = (TextView) rootView.findViewById(R.id.textViewProfileName);
final TextView textViewQuoteLike = (TextView) rootView.findViewById(R.id.textViewQuoteLike);
TextView textViewQuoteCopy = (TextView) rootView.findViewById(R.id.textViewQuoteCopy);
TextView textViewQuoteShare = (TextView) rootView.findViewById(R.id.textViewQuoteShare);
final TextView textViewQuoteId = (TextView) rootView.findViewById(R.id.textViewQuoteId);
textViewQuoteLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new GetDataLike().execute(textViewQuoteId.getText().toString());
String currentLike = textViewQuoteLike.getText().toString();
currentLike = currentLike.replace("پسندیدم (","");;
currentLike = currentLike.replace(")","");;
int newLike = Integer.valueOf(currentLike.toString()) + 1;
textViewQuoteLike.setText("پسندیدم ("+newLike+")");
}
});
return new ViewHolder(rootView, imageViewProfilePhoto, textViewQuoteContent, textViewProfileName, textViewQuoteLike, textViewQuoteCopy, textViewQuoteShare, textViewQuoteId);
}
}
static class GetDataLike extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Nullable
#Override
protected String doInBackground(String... params) {
String quoteId = params[0];
JSONObject jsonObject = JSONParser.getDataFromWeb("http://example.com/api-service/v1/platform_quote_like/?platform=true&id="+quoteId);
try {
if (jsonObject != null) {
if(jsonObject.length() > 0) {
JSONArray array = jsonObject.getJSONArray(Keys.KEY_LIKE);
int lenArray = array.length();
if(lenArray > 0) {
for(int jIndex = 0; jIndex < lenArray; jIndex++) {
JSONObject innerObject = array.getJSONObject(jIndex);
String quote_like = innerObject.getString(Keys.KEY_QUOTE_LIKE);
return quote_like;
}
}
}
} else {
}
} catch (JSONException je) {
Log.i(JSONParser.TAG, "" + je.getLocalizedMessage());
}
return null;
}
#Override
protected void onPostExecute(String aVoid) {
super.onPostExecute(aVoid);
}
}
public class CircleTransform implements Transformation {
#Override
public Bitmap transform(Bitmap source) {
int size = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - size) / 2;
int y = (source.getHeight() - size) / 2;
Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size);
if (squaredBitmap != source) {
source.recycle();
}
Bitmap bitmap = Bitmap.createBitmap(size, size, source.getConfig());
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint();
BitmapShader shader = new BitmapShader(squaredBitmap,
BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP);
paint.setShader(shader);
paint.setAntiAlias(true);
float r = size / 2f;
canvas.drawCircle(r, r, r, paint);
squaredBitmap.recycle();
return bitmap;
}
#Override
public String key() {
return "circle";
}
}
}
HomeFragment.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.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.adapter.QuoteArrayAdapter;
import com.example.model.QuoteDataModel;
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 HomeFragment extends Fragment {
private ListView listView;
private ArrayList<QuoteDataModel> list;
private QuoteArrayAdapter adapter;
private TextView likeCurrent;
public HomeFragment() {
// 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_home, 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 QuoteArrayAdapter(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).getProfileName() + " => " + list.get(position).getQuoteLike(), Snackbar.LENGTH_LONG).show();
}
});
/**
* Check internet connection
*/
if (!MainActivity.NetworkUtil.isOnline(getActivity().getApplicationContext())) {
Toast.makeText(getActivity(), "اتصال به اینترنت برقرار نیست",
Toast.LENGTH_LONG).show();
}
new GetDataHome().execute();
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if(firstVisibleItem+visibleItemCount == totalItemCount && totalItemCount!=0)
{
new GetDataHome().execute();
}
}
});
/*
likeCurrent = (TextView) getActivity().findViewById(R.id.textViewQuoteLike);
likeCurrent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
likeCurrent.setText("Boiling Point K");
}
});*/
}
/**
* Creating Get Data Task for Getting Data From Web
*/
class GetDataHome 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_home/?platform=true");
try {
/**
* Check Whether Its NULL???
*/
if (jsonObject != null) {
/**
* Check Length...
*/
if(jsonObject.length() > 0) {
/**
* Getting Array named "Home" From MAIN Json Object
*/
JSONArray array = jsonObject.getJSONArray(Keys.KEY_HOME);
/**
* 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
*/
QuoteDataModel model = new QuoteDataModel();
/**
* Getting Inner Object from contacts array...
* and
* From that We will get Name of that Contact
*
*/
JSONObject innerObject = array.getJSONObject(jIndex);
String profile_photo = innerObject.getString(Keys.KEY_PROFILE_PHOTO);
String profile_name = innerObject.getString(Keys.KEY_PROFILE_NAME);
String profile_link = innerObject.getString(Keys.KEY_PROFILE_LINK);
String quote_like = innerObject.getString(Keys.KEY_QUOTE_LIKE);
String quote_id = innerObject.getString(Keys.KEY_QUOTE_ID);
String quote_content = innerObject.getString(Keys.KEY_QUOTE_CONTENT);
String quote_category = innerObject.getString(Keys.KEY_QUOTE_CATEGORY);
/**
* Getting Object from Object "other"
*/
//JSONObject otherObject = innerObject.getJSONObject(Keys.KEY_NAME);
//String other = otherObject.getString(Keys.KEY_NAME_SUB);
model.setProfilePhoto(profile_photo);
model.setProfileName(profile_name);
model.setProfileLink(profile_link);
model.setQuoteLike(quote_like);
model.setQuoteId(quote_id);
model.setQuoteContent(quote_content);
model.setQuoteCategory(quote_category);
/**
* 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();
}
}
}
}
quote_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">
<ImageView
android:id="#+id/imageViewProfilePhoto"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_margin="5dp"
android:layout_gravity="right"
android:layout_alignParentRight="true"
android:src="#drawable/empty_profile_photo" />
<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/textViewQuoteContent"
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" />
<TextView
android:id="#+id/textViewProfileName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
android:textIsSelectable="true"
tools:text="Profile Name" />
<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">
<TextView
android:id="#+id/textViewQuoteCopy"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
android:clickable="true"
tools:text="Copy" />
<TextView
android:id="#+id/textViewQuoteShare"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
tools:text="Share" />
<TextView
android:id="#+id/textViewQuoteLike"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:textAppearance="?android:textAppearanceSmall"
tools:text="Like" />
</LinearLayout>
</LinearLayout>
<TextView
android:text="TextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/textViewQuoteId"
android:visibility="invisible" />
</RelativeLayout>
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android: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_centerInParent="true"
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" />
</RelativeLayout>
You just need a context, so:
Toast.makeText(rootView.getContext(), "Like is done.",
Toast.LENGTH_LONG).show();
But you need to make rootView final first:
public static ViewHolder create(final RelativeLayout rootView){...
^^

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!

TimePicker Dialog when clicking EditText

I used this question to get the timepicker when clicking on editext.
Please note that I am putting the code in a fragment.
What i've changed is the following:
Added : Context ctx; to the settime.java
On the line:
SetTime fromTime = new SetTime(chostime,this);
It is telling me : the constructor SetTime(editText, AppointFragment) is not defined.
I’ve tried to change it into :
SetTime fromTime = new SetTime(chostime,getActivity());
When trying to run the application gice me the following error
12-30 18:03:55.120: E/AndroidRuntime(1376): java.lang.NullPointerException
Here is the code :
AppointFragment.java
package com.example.appointapp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
public class AppointFragment extends Fragment{
private static final String TAG = "AppoinFragment";
EditText chosdate, chostime;
private Appointment mappointment;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mappointment= new Appointment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_appoint, parent, false);
chosdate = (EditText)v.findViewById(R.id.datea_text);
chostime = (EditText)v.findViewById(R.id.timea_text);
SetTime fromTime = new SetTime(chostime,this);
chosdate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
DialogFragment datePickerFragment = new DatePickerFragment() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
Log.d(TAG, "onDateSet");
Calendar c = Calendar.getInstance();
c.set(year, month, day);
String myFormat = "dd/MM/yy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
chosdate.setText(sdf.format(c.getTime()));
chosdate.requestFocus();
}
};
datePickerFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
}
}
});
return v;
}
}
SetTime.java
package com.example.appointapp;
import java.util.Calendar;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.TimePicker;
class SetTime implements OnFocusChangeListener, OnTimeSetListener {
private EditText editText;
private Calendar myCalendar;
Context ctx;
public SetTime(EditText editText, Context ctx){
this.editText = editText;
this.editText.setOnFocusChangeListener(this);
this.myCalendar = Calendar.getInstance();
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
int hour = myCalendar.get(Calendar.HOUR_OF_DAY);
int minute = myCalendar.get(Calendar.MINUTE);
new TimePickerDialog(ctx, this, hour, minute, true).show();
}
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
this.editText.setText( hourOfDay + ":" + minute);
}
}
First override onActivityCreated() in AppointFragment and then use the getActivity() to create SetTime object.
private SetTime fromTime;
private EditText chosdate, chostime;
...
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
fromTime = new SetTime(chostime,getActivity());
}
The complete code for setting the time using Fragments is below. You can use the same approach for setting the date too.
MainActivity.java
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create a new Fragment to be placed in the activity layout
ChildFragment firstFragment = new ChildFragment();
// In case this activity was started with special instructions from an
// Intent, pass the Intent's extras to the fragment as arguments
//firstFragment.setArguments(getIntent().getExtras());
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.frameLayout, firstFragment).commit();
}
ChildFragment.java (For displaying EditTexts)
public class ChildFragment extends Fragment implements View.OnClickListener, TimePickerFragment.Callback
{
private EditText editText;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.child_fragment, null, false);
editText = (EditText) view.findViewById(R.id.time_edit_text);
editText.setOnClickListener(this);
return view;
}
#Override
public void onClick(View view)
{
if(view == editText)
{
TimePickerFragment dialog = new TimePickerFragment();
dialog.setTargetFragment(this, 1); //request code
dialog.show(getFragmentManager(),"dialog");
}
}
#Override
public void onTimeSelected(String time)
{
editText.setText(time);
}
}
TimePickerFragment.java
public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
public interface Callback
{
public void onTimeSelected(String time);
}
private Callback timeCallback;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
timeCallback = (Callback) getTargetFragment();
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
timeCallback.onTimeSelected(hourOfDay + ":" + minute + ":00");
}
}
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">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/frameLayout"/>
</RelativeLayout>
child_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/time_edit_text"/>
</LinearLayout>
Here is the code :
AppointFragment.java
package com.example.appointapp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
public class AppointFragment extends Fragment{
private static final String TAG = "AppoinFragment";
EditText chosdate, chostime;
private Appointment mappointment;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mappointment= new Appointment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View v = inflater.inflate(R.layout.fragment_appoint, parent, false);
chosdate = (EditText)v.findViewById(R.id.datea_text);
chostime = (EditText)v.findViewById(R.id.timea_text);
SetTime fromTime = new SetTime(chostime,this);
chosdate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
DialogFragment datePickerFragment = new DatePickerFragment() {
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
Log.d(TAG, "onDateSet");
Calendar c = Calendar.getInstance();
c.set(year, month, day);
String myFormat = "dd/MM/yy";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
chosdate.setText(sdf.format(c.getTime()));
chosdate.requestFocus();
}
};
datePickerFragment.show(getActivity().getSupportFragmentManager(), "datePicker");
}
}
});
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
SetTime fromTime = new SetTime(chostime,getActivity());
}
}
SetTime.java
package com.example.appointapp;
import java.util.Calendar;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.TimePicker;
class SetTime implements OnFocusChangeListener, OnTimeSetListener {
private EditText editText;
private Calendar myCalendar;
Context ctx;
public SetTime(EditText editText, Context ctx){
this.editText = editText;
this.editText.setOnFocusChangeListener(this);
this.myCalendar = Calendar.getInstance();
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
int hour = myCalendar.get(Calendar.HOUR_OF_DAY);
int minute = myCalendar.get(Calendar.MINUTE);
new TimePickerDialog(ctx, this, hour, minute, true).show();
}
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
this.editText.setText( hourOfDay + ":" + minute);
}
}
SingleFragmentAcitivity.java
public abstract class SingleFragmentActivity extends FragmentActivity {
protected abstract Fragment createFragment();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
fragment = createFragment();
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit();
}
}
}
Appointactivity.java
package com.example.appointapp;
import android.support.v4.app.Fragment;
public class AppointActivity extends SingleFragmentActivity {
#Override
protected Fragment createFragment() {
return new AppointFragment();
}
}
Fragment_main.xml
<?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" >
<Button
android:id="#+id/new_patient"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/new_patient" />
<Button
android:id="#+id/new_appoint"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/new_appoint"/>
</LinearLayout>
Fragment_appoint.xml
<?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" >
<Spinner
android:id="#+id/Patients_list"
android:layout_width="117dp"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/datea_text"
android:layout_width="143dp"
android:layout_height="wrap_content"
android:hint="#string/datea_text_hint" />
<EditText
android:id="#+id/timea_text"
android:layout_width="141dp"
android:layout_height="wrap_content"
android:hint="#string/timea_text_hint" />
<Button
android:id="#+id/savea_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/savea_button" />
</LinearLayout>
Thank you for ur help
i solved the issue using the following code in my fragment:
chostime.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
chostime.setText( selectedHour + ":" + selectedMinute);
}
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();
}
});
Thank you

RecyclerView Data is not showing up

I am trying to create Navigation Drawer with RecyclerView. I am following a tutorial on YouTube to do this because I am new to this. The problem is RecyclerView does not show any data from the adapter. I need help. Any suggestion on this is appreciated.
NavigationDrawerFragment.java
package com.pixalstudio.cakedekho;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {#link Fragment} subclass.
*/
public class NavigationDrawerFragment extends Fragment {
int i=0;
private RecyclerView recyclerView;
public static final String PREF_FILE_NAME = "testpref";
public static final String KEY_USER_LEARNED_DRAWER = "user_learned_drawer";
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private InfoAdapter adapter;
private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;
private View containerView;
public NavigationDrawerFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mUserLearnedDrawer = Boolean.valueOf(readFromPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, "false"));
if (savedInstanceState != null) {
mFromSavedInstanceState = true;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View layout = inflater.inflate(R.layout.fragment_navigation_drawer, container, false);
recyclerView = (RecyclerView) layout.findViewById(R.id.drawerList);
adapter = new InfoAdapter(getActivity(), getData());
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return layout;
}
public List<Information> getData() {
List<Information> data = new ArrayList<>();
int[] icons = {R.drawable.seven1, R.drawable.seven2, R.drawable.seven3, R.drawable.seven4};
String[] titles = {"Login", "Location", "Home", "About Us"};
for (int i=0; i < titles.length && i < icons.length; i++) ;
{
Information current = new Information();
current.iconId = icons[i];
current.title = titles[i];
data.add(current);
}
return data;
}
public void setUp(int fragmentId, DrawerLayout drawerLayout, final Toolbar toolbar) {
containerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
mDrawerToggle = new ActionBarDrawerToggle(getActivity(), drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!mUserLearnedDrawer) {
mUserLearnedDrawer = true;
saveToPreferences(getActivity(), KEY_USER_LEARNED_DRAWER, mUserLearnedDrawer + "");
}
getActivity().invalidateOptionsMenu();
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActivity().invalidateOptionsMenu();
}
};
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(containerView);
}
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
}
public static void saveToPreferences(Context context, String preferenceName, String preferenceValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(preferenceName, preferenceValue);
editor.apply();
}
public static String readFromPreferences(Context context, String preferenceName, String defaultValue) {
SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
return sharedPreferences.getString(preferenceName, defaultValue);
}
}
Information.java
package com.pixalstudio.cakedekho;
/**
* Created by akkie on 7/10/2015.
*/
public class Information {
int iconId;
String title;
}
InfoAdapter.java
package com.pixalstudio.cakedekho;
import android.content.Context;
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 java.util.Collections;
import java.util.List;
/**
* Created by akkie on 7/10/2015.
*/
public class InfoAdapter extends RecyclerView.Adapter<InfoAdapter.MyViewHolder> {
List<Information> data = Collections.emptyList();
private LayoutInflater inflater;
public InfoAdapter(Context context, List<Information> data) {
inflater = LayoutInflater.from(context);
this.data = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.customrow, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Information current = data.get(position);
holder.title.setText(current.title);
holder.icon.setImageResource(current.iconId);
}
#Override
public int getItemCount() {
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder {
TextView title;
ImageView icon;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.listText);
icon = (ImageView) itemView.findViewById(R.id.listIcon);
}
}
}
customrow.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
>
<ImageView
android:id="#+id/listIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:padding="8dp"
android:src="#drawable/seven1" />
<TextView
android:id="#+id/listText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:padding="8dp"
android:text="Dummy Text" />
</LinearLayout>
fragment_navigation_drawer.xml
<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:background="#DADADA"
tools:context="com.pixalstudio.cakedekho.NavigationDrawerFragment">
<LinearLayout
android:id="#+id/containerDrawerImage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FB8C00">
<ImageView
android:layout_width="240dp"
android:layout_height="140dp"
android:src="#drawable/ic_abstract1" />
</LinearLayout>
<android.support.v7.widget.RecyclerView
android:layout_below="#+id/containerDrawerImage"
android:id="#+id/drawerList"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
Please let me know if anyone needs any other information to fix my problem. Thank you in advance.

Categories