Listview is not visible on Activity - java

I can't see my listview on Activity after adding a list item dynamically on floatingAction button click.
When I click on floatingActionButton, a new activity opens up which takes my input, after clicking on the save button ReminderActivity opens up but did not show input passed added in the list.
My motive is to add a new item in the listView every time after getting data from ReminderInputDataActivity which opens when I click on floating action button.
public class ReminderActivity extends AppCompatActivity {
private ListView lvReminder;
private FloatingActionButton floatingActionButton;
private ArrayList<Reminder> reminders;
public static final String REMINDER_INPUT = "reminder_input";
private ReminderCustomAdapter reminderListAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder);
reminders = new ArrayList<>();
lvReminder = (ListView) findViewById(R.id.lvReminder);
Intent getIntent = getIntent();
String[] reminderInput = getIntent.getStringArrayExtra(REMINDER_INPUT);
if (reminderInput != null) {
reminders.add(new Reminder(reminderInput[0], reminderInput[1], reminderInput[2]));
}
reminderListAdapter = new ReminderCustomAdapter(this, R.layout.listview_reminder, reminders);
lvReminder.setAdapter(reminderListAdapter);
floatingActionButton = (FloatingActionButton) findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(ReminderActivity.this, ReminderInputDataActivity.class);
startActivity(intent);
}
});
}
#Override
protected void onResume() {
super.onResume();
if (reminderListAdapter != null) {
reminderListAdapter.notifyDataSetChanged();
}
}
}
public class Reminder {
private String title;
private String date;
private String time;
public Reminder() {
}
public Reminder(String title, String date, String time) {
this.title = title;
this.date = date;
this.time = time;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
}
public class ReminderInputDataActivity extends AppCompatActivity {
private EditText etReminderTitle;
private Button btDate, btTime;
public static final String REMINDER_INPUT = "reminder_input";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.input_reminder);
etReminderTitle = (EditText) findViewById(R.id.etReminderTitle);
btDate = (Button) findViewById(R.id.btReminderDate);
btTime = (Button) findViewById(R.id.btReminderTime);
btDate.setText(new SimpleDateFormat("E, dd MMM yyyy", Locale.getDefault()).format(new Date()));
btTime.setText(new SimpleDateFormat("HH:mm:ss", Locale.getDefault()).format(new Date()));
Button btRemSave = (Button) findViewById(R.id.btRemSave);
Button btRemCancel = (Button) findViewById(R.id.btRemCancel);
final Intent intent = new Intent(ReminderInputDataActivity.this, ReminderActivity.class);
btRemSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] userInput = new String[3];
userInput[0] = etReminderTitle.getText() != null ? etReminderTitle.getText().toString() : "";
userInput[1] = btDate.getText().toString();
userInput[2] = btTime.getText().toString();
Bundle bundle = new Bundle();
bundle.putStringArray(REMINDER_INPUT, userInput);
intent.putExtras(bundle);
startActivity(intent);
}
});
btRemCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(intent);
}
});
}
}
public class ReminderCustomAdapter extends BaseAdapter {
private final Context mContext;
private int resource;
private ArrayList<Reminder> reminderList;
public ReminderCustomAdapter(Context mContext, int resource, ArrayList<Reminder> reminderList) {
this.mContext = mContext;
this.resource = resource;
this.reminderList = reminderList;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(resource, null);
TextView tvInputRemTitle = (TextView) view.findViewById(R.id.tvInputRemTitle);
TextView tvInputRemDate = (TextView) view.findViewById(R.id.tvInputRemDate);
TextView tvInputRemTime = (TextView) view.findViewById(R.id.tvInputRemTime);
Reminder reminder = reminderList.get(position);
tvInputRemTitle.setText(reminder.getTitle());
tvInputRemDate.setText(reminder.getDate());
tvInputRemTime.setText(reminder.getTime());
return view;
}
}
activity_reminder.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"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/lvReminder"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_margin="16dp"
android:backgroundTint="#color/colorPrimaryDark"
android:contentDescription="#string/reminder"
android:src="#android:drawable/ic_input_add"
app:shapeAppearanceOverlay="#style/fab_3_rounded" />
</RelativeLayout>
listview_reminder.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="#+id/tvInputRemTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Title"
android:textSize="15sp" />
<TextView
android:id="#+id/tvInputRemDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvInputRemTitle"
android:hint="Date" />
<TextView
android:id="#+id/tvInputRemTime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/tvInputRemTitle"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/tvInputRemDate"
android:hint="Time" />
</RelativeLayout>
I am new to android and started creating a basic project, for the above issue I watched some videos and go through articles but unable to get the issue here.
Please help. Thanks in Advance!

Problem is due to this code
final Intent intent = new Intent(ReminderInputDataActivity.this, ReminderActivity.class);
btRemSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String[] userInput = new String[3];
userInput[0] = etReminderTitle.getText() != null ? etReminderTitle.getText().toString() : "";
userInput[1] = btDate.getText().toString();
userInput[2] = btTime.getText().toString();
Bundle bundle = new Bundle();
bundle.putStringArray(REMINDER_INPUT, userInput);
intent.putExtras(bundle);
startActivity(intent);
}
});
Here you start ReminderActivity again which calls onCreate method of this activity, where you have added reminders = new ArrayList<>(); which recreate this arraylist with no data.
To Avoid this you can implement two solutions.
Implement interface.
StartActivityForResult.
Easiest solution would be StartActivityForResult.
For Example,
Intent intent = new Intent(ReminderActivity.this,ReminderInputDataActivity.class);
startActivityForResult(intent, 2);
and in the same activity implement the callback.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
String message=data.getStringExtra("MESSAGE");
textView1.setText(message);
}
}
From ReminderInputDataActivity send data back to this class like this.
Intent intent=new Intent();
intent.putExtra("MESSAGE",message);
setResult(2,intent);
finish();//finishing activity

Related

How to pass values from one class with on click method from other class

I have 2 Adapter classes with their Object class also:
First Adapter class is:
public class UpcomingAdpter extends RecyclerView.Adapter<UpcomingAdpter.ItemRowHolder> {
private ArrayList<UpcomingObject> itemList;
private Context context;
public UpcomingAdpter(ArrayList<UpcomingObject> itemList, Context context){
this.itemList = itemList;
this.context = context;
}
#Override
public ItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.upcominglayout, null);
ItemRowHolder mh = new ItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(ItemRowHolder itemRowHolder, int i) {
final String sectionName = itemList.get(i).getDate();
final ArrayList<SingleItemModelForUpcoming> singleSectionItems = itemList.get(i).getNamesList();
final ArrayList<SingleItemforPhoneNumbers> singleSectionItemsForPhoneNumber = itemList.get(i).getPhoneList();
itemRowHolder.date.setText(sectionName);
AdapterForNamesListInUpcoming itemListDataAdapter = new AdapterForNamesListInUpcoming(context, singleSectionItemsForPhoneNumber, singleSectionItems);
AdapterForNamesListInUpcoming itemListDataAdapterSecond = new AdapterForNamesListInUpcoming(context, singleSectionItemsForPhoneNumber, singleSectionItems);
itemRowHolder.recycler_view_list.setHasFixedSize(true);
itemRowHolder.recycler_view_list.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
itemRowHolder.recycler_view_list.setAdapter(itemListDataAdapter);
itemRowHolder.recycler_view_list.setAdapter(itemListDataAdapterSecond);
itemRowHolder.recycler_view_list.setNestedScrollingEnabled(false);
itemRowHolder.recycler_view_list.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("dd","here is me");
}
});
}
#Override
public int getItemCount() {
return (null != itemList ? itemList.size() : 0);
}
public class ItemRowHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected TextView date;
protected RecyclerView recycler_view_list;
public ItemRowHolder(View view) {
super(view);
this.date = (TextView) view.findViewById(R.id.date);
this.recycler_view_list = (RecyclerView) view.findViewById(R.id.recycler_view_list);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String finaldate = date.getText().toString();
Log.d("Date", "now date us "+finaldate);
}
}
}
The Object Class for this is :
public class UpcomingObject {
private String Date;
private ArrayList<SingleItemModelForUpcoming> NamesList;
private ArrayList<SingleItemforPhoneNumbers> PhoneList;
public UpcomingObject() {
}
public UpcomingObject(String Date, ArrayList<SingleItemModelForUpcoming> NamesList, ArrayList<SingleItemforPhoneNumbers> PhoneList) {
this.Date = Date;
this.NamesList = NamesList;
this.PhoneList = PhoneList;
}
public String getDate() {
return Date;
}
public void setDate(String date) {
Date = date;
}
public ArrayList<SingleItemModelForUpcoming> getNamesList() {
return NamesList;
}
public void setNamesList(ArrayList<SingleItemModelForUpcoming> namesList) {
NamesList = namesList;
}
public ArrayList<SingleItemforPhoneNumbers> getPhoneList() {
return PhoneList;
}
public void setPhoneList(ArrayList<SingleItemforPhoneNumbers> phoneList) {
PhoneList = phoneList;
}
}
The Layout for this is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
android:layout_marginLeft="50dp"
xmlns:app="http://schemas.android.com/apk/res-auto">
<TextView
android:id="#+id/date"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fontFamily="#font/gothic"
android:layout_marginTop="10dp"
android:textColor="#000"
android:text="10-10-2019"/>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_marginTop="40dp"
android:id="#+id/takedate"
android:layout_height="wrap_content">
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_view_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginTop="5dp"
android:layout_marginLeft="20dp"
android:orientation="vertical" />
</RelativeLayout>
The Second Adapter class is :
public class AdapterForNamesListInUpcoming extends RecyclerView.Adapter<AdapterForNamesListInUpcoming.SingleItemRowHolder> {
private List<SingleItemModelForUpcoming> itemsList;
private List<SingleItemforPhoneNumbers> itemforPhoneNumbers;
private Context mContext;
public AdapterForNamesListInUpcoming(Context context, List<SingleItemforPhoneNumbers> itemforPhoneNumbers , List<SingleItemModelForUpcoming> itemsList ) {
this.itemsList = itemsList;
this.itemforPhoneNumbers = itemforPhoneNumbers;
this.mContext = context;
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.upcomingclientlistlayout, null);
SingleItemRowHolder mh = new SingleItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {
SingleItemModelForUpcoming singleItem = itemsList.get(i);
SingleItemforPhoneNumbers singleItemforPhoneNumbers = itemforPhoneNumbers.get(i);
holder.nameofclient.setText(singleItem.getName());
holder.phoneNumber.setText(singleItemforPhoneNumbers.getPhoneNumber());
}
#Override
public int getItemCount() {
return (null != itemsList ? itemsList.size() : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected TextView nameofclient , phoneNumber, date;
public SingleItemRowHolder(View view) {
super(view);
this.nameofclient = (TextView) view.findViewById(R.id.nameofclient);
this.phoneNumber = (TextView)view.findViewById(R.id.phoneNumber);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent UpcomingDetailPage = new Intent(v.getContext(), com.allwaseet.spaservshop.UpcomingDetailsPage.UpcomingDetailPage.class);
v.getContext().startActivity(UpcomingDetailPage);
String finalPhoneNumber = phoneNumber.getText().toString();
Log.d("PhoneNumber from databse ","phone Number is "+finalPhoneNumber);
SharedPreferences.Editor PhoneNumberEditor;
SharedPreferences PhoneNumberSharedPreference;
PhoneNumberSharedPreference = mContext.getSharedPreferences("SelectedPhoneNumber", Context.MODE_PRIVATE);
PhoneNumberEditor = PhoneNumberSharedPreference.edit();
PhoneNumberEditor.putString("SelectedPhoneNumber",finalPhoneNumber);
PhoneNumberEditor.commit();
Log.d("PhoneNumber from databse ","phone Number is "+finalPhoneNumber);
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.upcominglayout, null, true);
TextView textView = (TextView)view.findViewById( R.id.date );
String finaldate = textView.getText().toString();
Log.d("ss","date is "+finaldate);
SharedPreferences.Editor DateEditor;
SharedPreferences DateSharedPreference;
DateSharedPreference = mContext.getSharedPreferences("DateInUpcoming", Context.MODE_PRIVATE);
DateEditor = DateSharedPreference.edit();
DateEditor.putString("DateInUpcoming",finaldate);
DateEditor.commit();
// return view;
}
}
}
Object class for this is :
public class SingleItemModelForUpcoming {
private String name;
public SingleItemModelForUpcoming(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Layout for this is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="550dp"
android:layout_marginTop="40dp"
android:layout_height="150dp"
android:layout_marginLeft="50dp"
android:paddingBottom="30dp"
android:orientation="horizontal"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="560dp"
android:background="#drawable/upcomingandhistorybackground"
android:layout_height="100dp">
<TextView
android:id="#+id/time"
android:layout_width="wrap_content"
android:text="2:30"
android:layout_marginTop="35dp"
android:textSize="25dp"
android:fontFamily="#font/gothic"
android:layout_marginLeft="20dp"
android:textColor="#fff"
android:layout_height="wrap_content" />
<View
android:layout_width="1dp"
android:layout_marginLeft="80dp"
android:layout_marginTop="15dp"
android:layout_height="70dp"
android:background="#fff"
/>
<TextView
android:id="#+id/nameofclient"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:layout_marginLeft="100dp"
android:layout_marginTop="35dp"
android:textColor="#fff"
android:fontFamily="#font/gothic"
android:textSize="20dp"/>
<!--Not in use-->
<TextView
android:id="#+id/phoneNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible"
android:layout_marginLeft="100dp"
android:layout_marginTop="4dp"
android:textColor="#fff"
android:text="rr"
android:fontFamily="#font/gothic"
android:textSize="20dp"/>
<!--Not in use-->
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:layout_marginLeft="495dp"
android:src="#drawable/rightarrow"/>
Now what I want is when I click the item which is present in the Second Adapter class, I want to take the date which is specified in the first adapter class. How can I do this.
This is the example picture
For example:
when I click on the pink portion or cell I should get the date also with it. But the problem is the date is specified in another adapter class
Any help would be appreciated.
use this
public class AdapterForNamesListInUpcoming extends RecyclerView.Adapter<AdapterForNamesListInUpcoming.SingleItemRowHolder> {
private List<SingleItemModelForUpcoming> itemsList;
private List<SingleItemforPhoneNumbers> itemforPhoneNumbers;
private ArrayList<UpcomingObject> item;
private Context mContext;
public AdapterForNamesListInUpcoming(Context context,ArrayList<UpcomingObject> item, List<SingleItemforPhoneNumbers> itemforPhoneNumbers , List<SingleItemModelForUpcoming> itemsList ) {
this.itemsList = itemsList;
this.item = item;
this.itemforPhoneNumbers = itemforPhoneNumbers;
this.mContext = context;
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.upcomingclientlistlayout, null);
SingleItemRowHolder mh = new SingleItemRowHolder(v);
return mh;
}
#Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {
SingleItemModelForUpcoming singleItem = itemsList.get(i);
SingleItemforPhoneNumbers singleItemforPhoneNumbers = itemforPhoneNumbers.get(i);
holder.nameofclient.setText(singleItem.getName());
holder.phoneNumber.setText(singleItemforPhoneNumbers.getPhoneNumber());
}
#Override
public int getItemCount() {
return (null != itemsList ? itemsList.size() : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
protected TextView nameofclient , phoneNumber, date;
public SingleItemRowHolder(View view) {
super(view);
this.nameofclient = (TextView) view.findViewById(R.id.nameofclient);
this.phoneNumber = (TextView)view.findViewById(R.id.phoneNumber);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
UpcomingObject up = item.get(getAdapterPosition);
Intent UpcomingDetailPage = new Intent(v.getContext(), com.allwaseet.spaservshop.UpcomingDetailsPage.UpcomingDetailPage.class);
v.getContext().startActivity(UpcomingDetailPage);
String finalPhoneNumber = phoneNumber.getText().toString();
Log.d("PhoneNumber from databse ","phone Number is "+finalPhoneNumber);
SharedPreferences.Editor PhoneNumberEditor;
SharedPreferences PhoneNumberSharedPreference;
PhoneNumberSharedPreference = mContext.getSharedPreferences("SelectedPhoneNumber", Context.MODE_PRIVATE);
PhoneNumberEditor = PhoneNumberSharedPreference.edit();
PhoneNumberEditor.putString("SelectedPhoneNumber",finalPhoneNumber);
PhoneNumberEditor.commit();
Log.d("PhoneNumber from databse ","phone Number is "+finalPhoneNumber);
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.upcominglayout, null, true);
TextView textView = (TextView)view.findViewById( R.id.date );
String finaldate = textView.getText().toString();
Log.d("ss","date is "+finaldate);
SharedPreferences.Editor DateEditor;
SharedPreferences DateSharedPreference;
DateSharedPreference = mContext.getSharedPreferences("DateInUpcoming", Context.MODE_PRIVATE);
DateEditor = DateSharedPreference.edit();
DateEditor.putString("DateInUpcoming",finaldate);
DateEditor.commit();
// return view;
}
});
}
}
}
You can pass data from one class to another class on click event of button or any item using Intent so you can do is that store your data of 1st class into Shared preference and then pass data in form of key value pair like this:
public class AdapterForNamesListInUpcoming extends
RecyclerView.Adapter<AdapterForNamesListInUpcoming.SingleItemRowHolder> {
private List<SingleItemModelForUpcoming> itemsList;
private List<SingleItemforPhoneNumbers> itemforPhoneNumbers;
private ArrayList<UpcomingObject> item;
private Context ctx;
public AdapterForNamesListInUpcoming(Context
context,ArrayList<UpcomingObject> item, List<SingleItemforPhoneNumbers>
itemforPhoneNumbers , List<SingleItemModelForUpcoming> itemsList ) {
this.itemsList = itemsList;
this.item = item;
this.itemforPhoneNumbers = itemforPhoneNumbers;
this.ctx = context;
}
#Override
public SingleItemRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v =
LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.upcomingclientlistlayout, null);
SingleItemRowHolder rh = new SingleItemRowHolder(v);
return rh;
}
#Override
public void onBindViewHolder(SingleItemRowHolder holder, int i) {
SingleItemModelForUpcoming singleItem = itemsList.get(i);
SingleItemforPhoneNumbers singleItemforPhoneNumbers =
itemforPhoneNumbers.get(i);
holder.nameofclient.setText(singleItem.getName());
holder.phoneNumber.setText(singleItemforPhoneNumbers.getPhoneNumber());
}
#Override
public int getItemCount() {
return (null != itemsList ? itemsList.size() : 0);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
protected TextView nameofclient , phoneNumber, date;
public SingleItemRowHolder(View view) {
super(view);
this.nameofclient = (TextView) view.findViewById(R.id.nameofclient);
this.phoneNumber = (TextView)view.findViewById(R.id.phoneNumber);
view.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// get data of first adapter
UpcomingObject up = item.get(getAdapterPosition);
Intent UpcomingDetailPage = new Intent(v.getContext(),
com.allwaseet.spaservshop.UpcomingDetailsPage.UpcomingDetailPage.class);
v.getContext().startActivity(UpcomingDetailPage);
String finalPhoneNumber = phoneNumber.getText().toString();
Log.d("PhoneNumber from databse ","phone Number is "+finalPhoneNumber);
SharedPreferences.Editor PhoneNumberEditor;
SharedPreferences PhoneNumberSharedPreference;
PhoneNumberSharedPreference =
ctx.getSharedPreferences("SelectedPhoneNumber", Context.MODE_PRIVATE);
PhoneNumberEditor = PhoneNumberSharedPreference.edit();
PhoneNumberEditor.putString("SelectedPhoneNumber",finalPhoneNumber);
PhoneNumberEditor.commit();
Log.d("PhoneNumber from databse ","phone Number is "+finalPhoneNumber);
LayoutInflater inflater = LayoutInflater.from(ctx);
View view = inflater.inflate(R.layout.upcominglayout, null, true);
TextView textView = (TextView)view.findViewById( R.id.date );
String finaldate = textView.getText().toString();
Log.d("ss","date is "+finaldate);
SharedPreferences.Editor DateEditor;
SharedPreferences DateSharedPreference;
DateSharedPreference = ctx.getSharedPreferences("DateInUpcoming",
Context.MODE_PRIVATE);
DateEditor = DateSharedPreference.edit();
DateEditor.putString("DateInUpcoming",finaldate);
DateEditor.commit();
// return view;
}
}
}

How to set Title of images based on image select in android

I am developing an android app, where I am trying to implement one feature for Image gallary. Now, initially, I want to show some image url with their title name. I am using hashmap for mapping title with their image.I have the model class with two String fields url and title. But The problem is I am very new in the development field and now sure how to show the title based on image click. Here is my model Class
public class ImageModel implements Parcelable {
String name, url;
public ImageModel() {
}
protected ImageModel(Parcel in) {
name = in.readString();
url = in.readString();
}
public static final Creator<ImageModel> CREATOR = new Creator<ImageModel>() {
#Override
public ImageModel createFromParcel(Parcel in) {
return new ImageModel(in);
}
#Override
public ImageModel[] newArray(int size) {
return new ImageModel[size];
}
};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(url);
}
}
Now the Main activity where I create a Hashmap with image and title to show those into views.
public class MainActivity extends AppCompatActivity {
GalleryAdapter mAdapter;
RecyclerView mRecyclerView;
ArrayList<ImageModel> data = new ArrayList<>();
ArrayList<HashMap<String, String>> arrayList = new ArrayList<>();
HashMap<String, String> h1 = new HashMap<>();
String[] imgUrls = {"https://images.unsplash.com/photo-1444090542259-0af8fa96557e?q=80&fm=jpg&w=1080&fit=max&s=4b703b77b42e067f949d14581f35019b",
"https://images.unsplash.com/photo-1439546743462-802cabef8e97?dpr=2&fit=crop&fm=jpg&h=725&q=50&w=1300",
"https://images.unsplash.com/photo-1441155472722-d17942a2b76a?q=80&fm=jpg&w=1080&fit=max&s=80cb5dbcf01265bb81c5e8380e4f5cc1"};
String[] imgNames = {"name1","name2","name3"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
for (int i = 0; i < 3; i++) { //change size according to your size.
ImageModel imageModel = new ImageModel();
imageModel.setName(imgNames[i]);
imageModel.setUrl(imgUrls[i]);
data.add(imageModel);
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mRecyclerView = (RecyclerView) findViewById(R.id.list);
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
mRecyclerView.setHasFixedSize(true);
mAdapter = new GalleryAdapter(MainActivity.this, data);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this,
new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putParcelableArrayListExtra("data", data);
intent.putExtra("pos", position);
startActivity(intent);
}
}));
}
}
GalleryAdapterCode
public class GalleryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
Context context;
List<ImageModel> data = new ArrayList<>();
public GalleryAdapter(Context context, List<ImageModel> data) {
this.context = context;
this.data = data;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
RecyclerView.ViewHolder viewHolder;
View v;
v = LayoutInflater.from(parent.getContext()).inflate(
R.layout.list_item, parent, false);
viewHolder = new MyItemHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Glide.with(context).load(data.get(position).getUrl())
.thumbnail(0.5f)
.override(200,200)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(((MyItemHolder) holder).mImg);
((MyItemHolder) holder).mTextView.setText(data.get(position).getName());
}
#Override
public int getItemCount() {
return data.size();
}
public static class MyItemHolder extends RecyclerView.ViewHolder {
ImageView mImg;
TextView mTextView;
public MyItemHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.textView);
mImg = (ImageView) itemView.findViewById(R.id.item_img);
}
}
}
My XML Class for item list row is
<?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"
android:weightSum="1">
<ImageView
android:id="#+id/item_img"
android:layout_width="match_parent"
android:layout_height="188dp"
android:adjustViewBounds="true"
android:background="#color/colorAccent"
android:contentDescription="#string/app_name"
android:scaleType="centerCrop"
android:src="#drawable/placeholder" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#7000"
android:orientation="vertical"
android:padding="10dp"
android:layout_alignBottom="#+id/item_img"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/textView"
android:text="Headline"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#FFF"
android:textSize="15dp"
android:textStyle="normal|bold"
/>
</LinearLayout>
</RelativeLayout>
Create two String arrays one containing image urls and other names in MainActivity.
String[] imgUrls = {"url1","url2","url3"};
String[] imgNames = {"name1","name2","name3"};
Iterate over those arrays and create a list of the model class.
ArrayList<ImageModel> data = new ArrayList<ImageModel>();
for (int i = 0; i < 3; i++) { //change size according to your size.
ImageModel imageModel = new ImageModel();
imageModel.setName(imgNames[i]);
imageModel.setUrl(imgUrls[i]);
data.add(imageModel);
}
mAdapter = new GalleryAdapter(MainActivity.this, data);
mRecyclerView.setAdapter(mAdapter);
Add a TextView in your RecyclerView row layout R.layout.list_item.
In your adapter use this TextView to set name of image.
public static class MyItemHolder extends RecyclerView.ViewHolder {
ImageView mImg;
TextView mTextView;
public MyItemHolder(View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.item_textview);
mImg = (ImageView) itemView.findViewById(R.id.item_img);
}
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
Glide.with(context).load(data.get(position).getUrl())
.thumbnail(0.5f)
.override(200,200)
.crossFade()
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(((MyItemHolder) holder).mImg);
holder.mTextView.setText(data.get(position).getName());
}
Rest of your code will be the same.

I have multiple recyclerViews ,which should appear after another XML view,

I have multiple recyclerViews ,which should appear after another XML view, but they just don't , am using an adapter class to manage this. after using log.v I found that the the functions itself"in Adappter class" arent called , and i don't know why ??
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<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="com.example.linah.movielessonapp.Detailed_Movie">
<TextView
android:id="#+id/MovieTitle"
... />
<ImageView
android:id="#+id/MovieImage"
.../>
<TextView
android:id="#+id/MovieReview"
... />
<Button
android:id="#+id/Favbutton"
... />
<TextView
android:id="#+id/Date"
... />
<TextView
android:id="#+id/Rate"
.../>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="#+id/Trailers_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/MovieReview" />
<android.support.v7.widget.RecyclerView
android:id="#+id/reviews_recycler_view"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/Trailers_recycler_view"
/>
</LinearLayout>
</RelativeLayout>
</ScrollView>
public class Detailed_Movie extends AppCompatActivity {
public static List<Movie_Details> movieDetailsList = new ArrayList<>();
private String ID;
public String Trailer_OR_Review = "trailer";
private boolean noConnection;
private boolean trailersDone;
private int trailersSize;
private static MoviesDetailedAdapter mAdapter;
private RecyclerView TrailerRecyclerView, ReviewsRecyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailed__movie);
TrailerRecyclerView = (RecyclerView) findViewById(R.id.Trailers_recycler_view);
ReviewsRecyclerView = (RecyclerView) findViewById(R.id.reviews_recycler_view);
new getData().execute("trailer");
// adapter
mAdapter = new MoviesDetailedAdapter(movieDetailsList,TrailerRecyclerView.getContext(),Trailer_OR_Review);
// mAdapter = new MoviesDetailedAdapter(movieDetailsList,ReviewsRecyclerView.getContext(),Trailer_OR_Review);
TrailerRecyclerView.setLayoutManager(new LinearLayoutManager(TrailerRecyclerView.getContext()));
// ReviewsRecyclerView.setLayoutManager(new LinearLayoutManager(ReviewsRecyclerView.getContext()));
TrailerRecyclerView.setItemAnimator(new DefaultItemAnimator());
// ReviewsRecyclerView.setItemAnimator(new DefaultItemAnimator());
noConnection = false;
if(isOnline(Detailed_Movie.this)) {
new getData().execute("trailer");
mAdapter.notifyDataSetChanged();
}
// set the adapter
TrailerRecyclerView.setAdapter(mAdapter);
prepareMovieData();
Intent i = getIntent();
// http://api.themoviedb.org/3/movie/{id}/videos
String ImgPath = "http://image.tmdb.org/t/p/w185/";
String VideoPath = "http://www.youtube.com/watch?v=";
String MovieTitle = i.getExtras().getString("title");
Toast.makeText(getApplicationContext(),MovieTitle+" is selected!", Toast.LENGTH_SHORT).show();
ImageView img = (ImageView)findViewById(R.id.MovieImage);
TextView Title = (TextView)findViewById(R.id.MovieTitle);
TextView Review = (TextView)findViewById(R.id.MovieReview);
TextView Date = (TextView)findViewById(R.id.Date);
TextView Rate = (TextView)findViewById(R.id.Rate);
Button Fav = (Button) findViewById(R.id.Favbutton);
// get data from intent
assert Title != null;
Title. setText(i.getExtras().getString("title"));
assert Review != null;
Review.setText(i.getExtras().getString("review"));
assert Rate != null;
Rate. setText(i.getExtras().getString("rate"));
assert Date != null;
Date. setText(i.getExtras().getString("date"));
ID = i.getExtras().getString("id");
String Imgurl = i.getExtras().getString("img");
// append ImgPath
switch (ImgPath = new StringBuilder()
.append(ImgPath)
.append(Imgurl)
.toString()) {
}
// append VideoPath
VideoPath = new StringBuilder()
.append(VideoPath)
.append("6uEMl2BtcqQ")
.toString();
// VideoPath = VideoPath + getString(R.string.API_KEY);
final String finalVideoPath = VideoPath;
if (Fav != null) {
Fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(finalVideoPath));
startActivity(intent);
}
});
}
Picasso.with(this)
.load(ImgPath)
.placeholder(R.drawable.loading) //this is optional the image to display while the url image is downloading
.error(R.drawable.error) //this is also optional if some error has occurred in downloading the image
.into(img);
TrailerRecyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), TrailerRecyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
Movie_Details movie = movieDetailsList.get(position);
if (position < trailersSize) {
// String link = ((TextView) findViewById(R.id.Link)).getText().toString();
// String link = movie.getKey();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v=" + movie.getKey())));
}
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
private void prepareMovieData() {
Movie_Details movie = new Movie_Details("MovieTrailer","6uEMl2BtcqQ","Linah","verynice");
movieDetailsList.add(movie);
mAdapter.notifyDataSetChanged();
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
public static class RecyclerTouchListener implements RecyclerView.OnItemTouchListener {
private GestureDetector gestureDetector;
private MainActivity.ClickListener clickListener;
public RecyclerTouchListener(Context context, final RecyclerView recyclerView, final MainActivity.ClickListener clickListener) {
this.clickListener = clickListener;
gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildPosition(child));
}
}
});
}
public RecyclerTouchListener(Context applicationContext, RecyclerView trailerRecyclerView, ClickListener clickListener) {
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null && gestureDetector.onTouchEvent(e)) {
clickListener.onClick(child, rv.getChildPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
public class getData extends AsyncTask<String, Void, Void> {
...
}
}
class MoviesDetailedAdapter
public class MoviesDetailedAdapter extends RecyclerView.Adapter {
private List<Movie_Details> moviesList;
private Context context;
public String Trailer_OR_Review = "trailer";
public TextView TrailerName , Author , Content , TrailerLink ;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
public MyViewHolder(View view) {
super(view);
Log.v("here","MyViewHolder");
TrailerName = (TextView) view.findViewById(R.id.Name);
Author = (TextView) view.findViewById(R.id.Author);
TrailerLink = (TextView) view.findViewById(R.id.Link);
Content = (TextView) view.findViewById(R.id.Content);
view.setOnCreateContextMenuListener(this);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
}
}
public MoviesDetailedAdapter(List<Movie_Details> moviesList,Context context, String trailerORReview) {
this.moviesList = moviesList;
this.context = context;
Trailer_OR_Review = trailerORReview;
Log.v("here","madapter");
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView;
Log.v("here","onCreateViewHolder");
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.trailers_layout, parent, false);
/*
if (Trailer_OR_Review.equals("trailers")){
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.trailers_layout, parent, false);
}
else{
itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.reviews_layout, parent, false);
}*/
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
Log.v("here","onBindViewHolder");
Movie_Details movie_details = moviesList.get(position);
Log.v("here",movie_details.getContent());
Log.v("here",movie_details.getName());
TrailerName.setText(movie_details.getName());
TrailerLink.setText(movie_details.getKey());
/*
if (Trailer_OR_Review.equals("trailers")){
TrailerName.setText(movie_details.getName());
TrailerLink.setText(movie_details.getKey());
}
else{
Author.setText(movie_details.getAuthor());
Content.setText(movie_details.getContent());
}*/
}

Android loses content when rotate device or re-open APP without logout

I'm create a items list with CardViews and RecyclerView.
When I rotate, re-open the APP without logout or re-create the activity the content is lost. The content is displayed only when you first create the activity (after Login in APP).
I'm not sure why it may be happening and I wonder if someone could help me out.
I put the code here:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
DrawerLayout drawerLayout;
Toolbar toolbar;
ActionBar actionBar;
TextView textView;
Intent intent;
private SQLiteHandler db;
private SessionManager session;
private RecyclerView recycler;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager lManager;
private ProgressDialog pDialog;
JSONParser jParser;
private static final String TAG_SUCCESS = "success";
private static final String TAG_itemS = "items";
private static final String TAG_item_ID = "item_id";
private static final String TAG_NAME = "name";
private static final String TAG_USERNAME = "username";
private static final String TAG_PHOTO = "photo";
List<item> items;
JSONArray items = null;
HashMap<String, String> user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
items = new ArrayList<>();
new LoadAllitems().execute();
recycler = (RecyclerView) findViewById(R.id.recycler);
recycler.setHasFixedSize(true);
lManager = new LinearLayoutManager(this);
recycler.setLayoutManager(lManager);
adapter = new itemAdapter(items);
recycler.setAdapter(adapter);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
actionBar = getSupportActionBar();
actionBar.setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
actionBar.setDisplayHomeAsUpEnabled(true);
drawerLayout = (DrawerLayout) findViewById(R.id.navigation_drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.navigation_view);
if (navigationView != null) {
setupNavigationDrawerContent(navigationView);
View header = (View)getLayoutInflater().inflate(R.layout.navigation_drawer_header, null);
TextView navheaduser = (TextView) header.findViewById(R.id.usernameSession);
navheaduser.setText("asdfa");
}
setupNavigationDrawerContent(navigationView);
db = new SQLiteHandler(getApplicationContext());
session = new SessionManager(getApplicationContext());
if (!session.isLoggedIn()) {
logoutUser();
}
user = db.getUserDetails();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_allitems, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private void setupNavigationDrawerContent(NavigationView navigationView) {
navigationView.setNavigationItemSelectedListener(
new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
switch (menuItem.getItemId()) {
case R.id.item_navigation_drawer_allitems:
menuItem.setChecked(true);
drawerLayout.closeDrawer(GravityCompat.START);
intent = new Intent(MainActivity.this, MainActivity.class);
return true;
case R.id.item_navigation_drawer_myitems:
menuItem.setChecked(true);
drawerLayout.closeDrawer(GravityCompat.START);
intent = new Intent(MainActivity.this, Myitems.class);
return true;
case R.id.item_navigation_drawer_logout:
menuItem.setChecked(true);
drawerLayout.closeDrawer(GravityCompat.START);
logoutUser();
return true;
}
return true;
}
});
}
public static Drawable LoadImageFromWebOperations(String url) {
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
} catch (Exception e) {
return null;
}
}
private void logoutUser() {
session.setLogin(false);
db.deleteUsers();
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
class LoadAllitems extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage(getResources().getString(R.string.loadingitems));
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All items from url
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
jParser = new JSONParser();
JSONObject json = jParser.makeHttpRequest(AppConfig.URL_GET_ALL_itemS, "GET", params);
// Check your log cat for JSON reponse
Log.d("All items: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// items found
// Getting Array of items
items = json.getJSONArray(TAG_itemS);
// looping through All items
for (int i = 0; i < items.length(); i++) {
JSONObject c = items.getJSONObject(i);
items.add(new item(c.getInt(TAG_item_ID), getResources().getIdentifier(String.valueOf(LoadImageFromWebOperations(c.getString(TAG_PHOTO))), "drawable", getPackageName()), c.getString(TAG_NAME), c.getString(TAG_USERNAME)));
}
pDialog.dismiss();
} else {
// no items found
pDialog.dismiss();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
itemAdapter.class:
public class itemAdapter extends RecyclerView.Adapter<itemAdapter.itemViewHolder> {
private List<item> items;
public static class itemViewHolder extends RecyclerView.ViewHolder {
public ImageView image;
public TextView name;
public TextView userName;
//public TextView description;
public TextView username;
public itemViewHolder(View v) {
super(v);
image = (ImageView) v.findViewById(R.id.itemImage);
name = (TextView) v.findViewById(R.id.itemName);
//userName = (TextView) v.findViewById(R.id.userName);
//description = (TextView) v.findViewById(R.id.itemdescription);
username = (TextView) v.findViewById(R.id.username);
}
}
public itemAdapter(List items) {
this.items = items;
}
#Override
public int getItemCount() {
return items.size();
}
#Override
public itemViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_card, viewGroup, false);
return new itemViewHolder(v);
}
#Override
public void onBindViewHolder(itemViewHolder viewHolder, int i) {
viewHolder.image.setImageResource(items.get(i).getImagen());
viewHolder.name.setText(items.get(i).getName());
viewHolder.username.setText(viewHolder.username.getText() + " " + String.valueOf(items.get(i).getUsernamer()));
}
}
item.class:
public class item {
private int item_id;
private int image;
private String name;
private String username;
private String description;
public item(int item_id, int imagen, String name, String username) {
this.item_id = item_id;
this.image = imagen;
this.name = name;
this.username = username;
this.description = description;
}
public int getitem_id() {
return item_id;
}
public String getName() {
return name;
}
public String getUsernamer() {
return username;
}
public String getdescription() {
return description;
}
public int getImagen() {
return image;
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/navigation_drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="#bool/fitsSystemWindows">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="#dimen/status_bar_height"
android:background="?colorPrimary"/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="#dimen/status_bar_height"
android:background="?colorPrimaryDark"/>
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/status_bar_height">
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="3dp"
android:layout_marginTop="55dp"
android:scrollbars="vertical" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:theme="#style/ToolbarTheme" />
</FrameLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="#bool/fitsSystemWindows"
app:headerLayout="#layout/navigation_drawer_header"
app:menu="#menu/navigation_drawer_menu"
app:theme="#style/NavigationViewTheme" />
</android.support.v4.widget.DrawerLayout>
item_card.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_width="match_parent"
android:layout_height="150dp"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="4dp"
card_view:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/itemImage"
android:layout_width="100dp"
android:layout_height="150dp"
android:scaleType="centerCrop" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/itemName"
android:textColor="#666"
android:layout_toRightOf="#+id/itemImage"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="#string/userTag"
android:id="#+id/username"
android:textColor="#666"
android:layout_below="#+id/itemName"
android:layout_alignLeft="#+id/itemName" />
<View
android:layout_width="wrap_content"
android:layout_height="1dp"
android:background="#ffd5d5d5"
android:id="#+id/linea"
android:layout_toRightOf="#+id/itemImage">
</View>
</RelativeLayout>
</android.support.v7.widget.CardView>
Can anyone help me? I'm searching and trying for fix it but I can't make it work.
Thanks!!
EDIT:
I added this code and now the list is loader on rotate an re-create the activity, but the list is duplicated adding itself.
#Override
protected void onSaveInstanceState(Bundle outState){
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("ITEMS", items);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
items.clear();
items = savedInstanceState.getParcelableArrayList("ITEMS");
adapter = new itemAdapter(items);
recycler.setAdapter(adapter);
}
Android recreates the layout everytime you rotate your device. Therefore, if
you want the user to be able to rotate the device (orientation change), you have
to override the Activity method onSaveInstanceState and provide a Bunde
with all your needed information's.
After the orientation is changed, this bundle will be given to you in
protected void onCreate(Bundle savedInstanceState)
so you can recreate your views and activity state.
Edit: also do not forget to finish your AsyncTask
Edit: I already added a small explanation what you need to do, but in this
case I think a Google link is valid: Recreating an Activity
As said, Android will recreate your Activity, everytime you change the orientation of your device. Because the layout needs to reinflate etc..
initialize your app in onCreate
do your activity logic while the activity is active
if the activity goes into background onSaveInstanceState is called
save ALL your needed information's in the bundle (which is given as an arguement to the method)
your activity is recreated
fetch your saved information's from the bundle given to onCreate
You can use the #JacksOnF1re solution or add this in your manifest in the activity that require
android:configChanges="orientation|screenSize"
Any additional code is not necessary in your case.

SherlockfragmentActivity and sherlockListFragment

I'm trying to make a drobdown navigation menu so i can move between my pages using SherlockFragmentActivity and SerlockListFragment
but every time i'm starting my app it's give this following error:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.download.manager/com.download.manager.Main}: java.lang.RuntimeException: Your content must have a ListView whose id attribute is android.R.id.list
this is SherlockFragmentActivity class
public class Main extends SherlockFragmentActivity implements OnNavigationListener{
private static final String KEY_MODELS="models";
private static final String KEY_POSITION="position";
private static final String[] labels= { "All", "Downloads","Completed","Later" };
private CharSequence[] models=new CharSequence[4];
private DownloadList frag=null;
private int lastPosition=-1;
ActionBar act;
ViewPager myviewpager;
int mSelectedPageIndex=1;
DownloadService downloadservice;
Intent serviceIntent ;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
frag=(DownloadList)getSupportFragmentManager().findFragmentById(android.R.id.content);
if (frag==null) {
frag=new DownloadList();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, frag).commit();
}
if (state != null) {
models=state.getCharSequenceArray(KEY_MODELS);
}
if (downloadservice==null)
downloadservice= new DownloadService();
ArrayAdapter<String> nav=null;
act=getSupportActionBar();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
{
nav= new ArrayAdapter<String>( act.getThemedContext(),android.R.layout.simple_spinner_item,labels);
}
else
{
nav=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,labels);
}
nav.setDropDownViewResource(android.R.layout.simple_list_item_1);
act.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
act.setDisplayShowTitleEnabled(false);
act.setHomeButtonEnabled(false);
act.setListNavigationCallbacks(nav, this);
if (state != null) {
act.setSelectedNavigationItem(state.getInt(KEY_POSITION));
}
serviceIntent= new Intent(Main.this,downloadservice.getClass());
if (startService(serviceIntent)==null)
startService(serviceIntent);
act.setTitle("");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater infalter = getSupportMenuInflater();
infalter.inflate(R.menu.mymenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.sub1)
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Downlaod New File");
alert.setMessage("Enter URL");
final EditText input = new EditText(this);
alert.setView(input);
input.setText("http://205.196.123.184/ddpha7c5b8lg/616c36j0d1xbztf /Lecture+ppt+Ch2.ppt");
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
Log.d("value",value);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alert.show();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
lastPosition=itemPosition;
return false;
}
this is SherlockListFragment class
public class DownloadList extends SherlockListFragment {
int index=0;
Button downloadButton;
Button pauseButton;
Button resumeButton;
TextView textLink;
TextView progressbar;
DownloadService downloadservice= new DownloadService();
MyAdapter listadapter;
Intent serviceIntent ;
String state;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getActivity().setContentView(R.layout.downloadlist);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container,BundlesavedInstanceState) {
View rootView = inflater.inflate(R.layout.downloadlist, container, false);
return rootView;
}
int getIndex()
{
return index;
}
public class MyAdapter extends ArrayAdapter<NewDownload>
{
private final List<NewDownload> list;
private final Activity context;
Thread t;
public MyAdapter(Context context,List<NewDownload> list) {
super(context, R.layout.list_item, list);
this.context = (Activity) context;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getActivity().
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_item, null);
pauseButton = (Button) row.findViewById(R.id.btn1);
resumeButton = (Button) row.findViewById(R.id.btn2);
textLink = (TextView) row.findViewById(R.id.tv1);
progressbar = (TextView) row.findViewById(R.id.progressBar1);
textLink.setText(downloadservice.
downloads.get(position).getName());
progressbar.setBottom(downloadservice.
downloads.get(position).getDownloadedSize());
progressbar.setTop(downloadservice.
downloads.get(position).getTotalSize());
final int p = position;
final NewDownload r = list.get(p);
if (r.state=="downloading")
{
progressbar.setText("DownLoading...");
pauseButton.setEnabled(true);
resumeButton.setEnabled(false);
}
else if (r.state=="pause")
{
pauseButton.setEnabled(false);
resumeButton.setEnabled(true);
progressbar.setText(r.state);
}
pauseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
downloadservice.pause(p);
setListAdapter(listadapter );
}
});
resumeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (getActivity().startService(serviceIntent)==null)
getActivity().startService(serviceIntent);
downloadservice.resume(p);
setListAdapter(listadapter );
}
});
return row;
}
}
this is downloadlist.xml
<ListView
android:id="#+id/list" xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
this is list_item.XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="File Name" />
<TextView
android:id="#+id/progressBar1"
android:layout_width="306dp"
android:layout_height="wrap_content"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/btn1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="34dp"
android:layout_gravity="center_horizontal"
android:text="Pause" />
<Button
android:id="#+id/btn2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="34dp"
android:layout_gravity="right"
android:text="Resume" />
</LinearLayout>
</LinearLayout>
So any one can tell me where is my mistake ?
This error:
Your content must have a ListView whose id attribute is android.R.id.list
means you must use:
<ListView
android:id="#android:id/list"
...
in download.xml.

Categories