I have to make a listview from database and i want to put a image that is clickable in my list.I use CursorAdapter for it,but my image does not show on my list.Here is my BooksCursorAdapter
public class BooksCursorAdapter extends CursorAdapter {
public BooksCursorAdapter(Context context, Cursor c) {
super(context, c, 0 );
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.books_list_item, parent, false);
}
#Override
public void bindView(View view,final Context context, Cursor cursor) {
TextView productText = view.findViewById(R.id.productText);
TextView priceText = view.findViewById(R.id.priceText);
TextView quantityText = view.findViewById(R.id.quantityText);
ImageView shopButton = view.findViewById(R.id.shop_button);
int productColumnIndex = cursor.getColumnIndex(BooksContract.BooksEntry.COLUMN_BOOKS_PRODUCT);
int priceColumnIndex = cursor.getColumnIndex(BooksContract.BooksEntry.COLUMN_BOOKS_PRICE);
final int quantityColumnIndex = cursor.getColumnIndex(BooksContract.BooksEntry.COLUMN_BOOKS_QUANTITY);
String bookProduct = cursor.getString(productColumnIndex);
String bookPrice = cursor.getString(priceColumnIndex);
final int bookQuantity = cursor.getInt(quantityColumnIndex);
productText.setText(bookProduct);
priceText.setText(bookPrice);
quantityText.setText(Integer.toString(bookQuantity));
int idColumnIndex = cursor.getColumnIndex(BooksContract.BooksEntry._ID);
final int booksId = cursor.getInt(idColumnIndex);
shopButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Uri currentUri = ContentUris.withAppendedId(BooksContract.BooksEntry.CONTENT_URI, booksId);
makeSale(context, bookQuantity, currentUri);
}
});
}
private void makeSale(Context context, int bookQuantity, Uri uri) {
if (bookQuantity == 0) {
Toast.makeText(context, R.string.no_books, Toast.LENGTH_SHORT).show();
} else {
int newQuantity = bookQuantity - 1;
ContentValues values = new ContentValues();
values.put(BooksContract.BooksEntry.COLUMN_BOOKS_QUANTITY, newQuantity);
context.getContentResolver().update(uri, values, null, null);
}
}
}
Everything works fine and how it should be only that my image is not showing.
My book_list_item.xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:orientation="horizontal">
<LinearLayout
android:layout_width="333dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="#dimen/activity_margin">
<TextView
android:id="#+id/productText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-medium"
android:textAppearance="?android:textAppearanceMedium"
android:textColor="#2B3D4D" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/priceText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:textAppearance="?android:textAppearanceSmall"
android:textColor="#AEB6BD"
android:padding="5dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/currencyTextList" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/quantityTextList"
android:padding="5dp"/>
<TextView
android:id="#+id/quantityText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:textAppearance="?android:textAppearanceSmall"
android:textColor="#AEB6BD" />
</LinearLayout>
</LinearLayout>
<ImageView
android:layout_width="52dp"
android:layout_height="match_parent"
android:src="#drawable/shop_button"
android:id="#+id/shop_button"/>
</LinearLayout>
The image appears in my preview but not on my phone.I want to display an image stored on xml, that I can click on.
I did what #crammeur said, in second LinearLayout i replaced android:layout_width="333dp" with android:layout_width="0dp" and add android:layout_weight="1"
Related
So I am working on a tasks app. I am trying to set up a functionality, that might sound a little complicated, but I want to put it to work. Hear me out : User types in a task name, and then clicks on an 'add subtask ' button. That takes him to another activity, where he types in his subtask name (edit text), and also tells me the priority of the task, and the amount of time it will take (users answers this in the form of radio buttons). Then, he clicks on the 'done' button, from which he is taken back to the previous activity, where he entered the task name. What I want, is that the subtask name, along with symbols of the priority and time are shown in a list there. I transfer the data of the subtask activity using intents, then I have also made a subtask object, which accepts the subtask name, and boolean values of the radio buttons. I also made a custom adapter class for my listview. But the issue is, it is just not showing. This is my code :
The subtask object class :
public class subtask {
private String subtaskName;
private boolean priHigh;
private boolean priMed;
private boolean priLow;
private boolean timeMore;
private boolean timeMed;
private boolean timeLess;
public subtask(String subtaskName, boolean priHigh, boolean priMed, boolean priLow, boolean timeMore, boolean timeMed, boolean timeLess) {
this.subtaskName = subtaskName;
this.priHigh = priHigh;
this.priMed = priMed;
this.priLow = priLow;
this.timeMore = timeMore;
this.timeMed = timeMed;
this.timeLess = timeLess;
}
public String getSubtaskName() {
return subtaskName;
}
public boolean isPriHigh() {
return priHigh;
}
public boolean isPriMed() {
return priMed;
}
public boolean isPriLow() {
return priLow;
}
public boolean isTimeMore() {
return timeMore;
}
public boolean isTimeMed() {
return timeMed;
}
public boolean isTimeLess() {
return timeLess;
}
}
The adapter class :
public class SubtaskAdapter extends ArrayAdapter<subtask> {
private final Context context;
private final ArrayList<subtask> values;
public SubtaskAdapter(Context context, ArrayList<subtask> list) {
super(context, R.layout.subtask_item, list);
this.context = context;
this.values = list;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.subtask_item, parent, false);
TextView tvSubtaskName = rowView.findViewById(R.id.tvSubtaskName);
ImageView ivPri = rowView.findViewById(R.id.ivPri);
ImageView ivTime = rowView.findViewById(R.id.ivTime);
tvSubtaskName.setText(values.get(position).getSubtaskName());
if (values.get(position).isPriHigh())
{
ivPri.setImageResource(R.drawable.priority_high);
}
else if (values.get(position).isPriMed())
{
ivPri.setImageResource(R.drawable.priority_med);
}
else if (values.get(position).isPriLow())
{
ivPri.setImageResource(R.drawable.priority_low);
}
if (values.get(position).isTimeMore())
{
ivTime.setImageResource(R.drawable.time_symbol_more);
}
else if (values.get(position).isTimeMed())
{
ivTime.setImageResource(R.drawable.time_symbol_med);
}
else if (values.get(position).isTimeLess())
{
ivTime.setImageResource(R.drawable.time_symbol_less);
}
return rowView;
}
}
Here I receive the input from the subtasks activity and try and put it in the listview :
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == ENTER_SUBTASK)
{
if (resultCode == RESULT_OK)
{
String subtaskName = data.getStringExtra("subtaskName");
boolean priHigh = data.getBooleanExtra("priHigh", false);
boolean priMed = data.getBooleanExtra("priMed", false);
boolean priLow = data.getBooleanExtra("priLow", false);
boolean timeMore = data.getBooleanExtra("timeMore", false);
boolean timeMed = data.getBooleanExtra("timeMed", false);
boolean timeLess = data.getBooleanExtra("timeLess", false);
subtask subtask = new subtask(subtaskName, priHigh, priMed, priLow, timeMore, timeMed, timeLess);
subtaskList.add(subtask);
SubtaskAdapter adapter = new SubtaskAdapter(this, subtaskList);
lvSubtasks.setAdapter(adapter);
}
}
}
xml for the main activity :
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/background"
tools:context=".TaskInfo">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteY="163dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/floating_hint_taskname"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:counterEnabled="true"
app:counterMaxLength="20"
app:counterTextColor="#color/white"
app:hintTextAppearance="#style/FlotatingHintStyle">
<EditText
android:id="#+id/etTaskName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:ems="10"
android:fontFamily="#font/roboto"
android:hint="#string/name_your_task"
android:inputType="textPersonName"
android:maxLength="20"
android:textColor="#color/black"
android:textColorHint="#B8AEAE"
android:textSize="14sp" />
</com.google.android.material.textfield.TextInputLayout>
<ListView
android:id="#+id/lvSubtasks"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button
android:id="#+id/btnNewSubtask"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_marginTop="5dp"
android:layout_marginRight="32dp"
android:layout_marginBottom="16dp"
android:fontFamily="#font/roboto"
android:text="#string/add_subtask" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/tvEnterTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="8dp"
android:fontFamily="#font/roboto"
android:text="#string/estimated_working_time"
android:textColor="#B8AEAE"
android:textSize="16sp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/floating_hint_time_hrs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:hintTextAppearance="#style/FlotatingHintStyle">
<EditText
android:id="#+id/etWorkingHrs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_weight="1"
android:ems="10"
android:fontFamily="#font/roboto"
android:hint="#string/hours"
android:inputType="number"
android:maxLength="2"
android:textColorHint="#B8AEAE"
android:textSize="14sp" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/floating_hint_time_mins"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:hintTextAppearance="#style/FlotatingHintStyle">
<EditText
android:id="#+id/etWorkingMins"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:ems="10"
android:fontFamily="#font/roboto"
android:hint="#string/minutes"
android:inputType="number"
android:maxLength="2"
android:textColorHint="#B8AEAE"
android:textSize="14sp" />
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>
<TextView
android:id="#+id/tvMaxTimeWithoutBreak"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="32dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="16dp"
android:fontFamily="#font/roboto"
android:text="#string/time_you_can_work_for_without_a_break"
android:textColor="#B8AEAE"
android:textSize="16sp" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/floating_hint_time_hours"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:hintTextAppearance="#style/FlotatingHintStyle">
<EditText
android:id="#+id/etWorkingHours"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:layout_weight="1"
android:ems="10"
android:fontFamily="#font/roboto"
android:hint="#string/hours"
android:inputType="number"
android:maxLength="2"
android:textColorHint="#B8AEAE"
android:textSize="14sp" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/floating_hint_time_minutes"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:hintTextAppearance="#style/FlotatingHintStyle">
<EditText
android:id="#+id/etWorkingMinutes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="16dp"
android:ems="10"
android:fontFamily="#font/roboto"
android:hint="#string/minutes"
android:inputType="number"
android:maxLength="2"
android:textColorHint="#B8AEAE"
android:textSize="14sp" />
</com.google.android.material.textfield.TextInputLayout>
</LinearLayout>
<TextView
android:id="#+id/tvBreakDuration"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginTop="32dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="16dp"
android:fontFamily="#font/roboto"
android:text="#string/break_duration"
android:textColor="#B8AEAE"
android:textSize="16sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/ivLeft"
android:layout_width="56dp"
android:layout_height="56dp"
android:layout_weight="1"
android:clickable="true"
android:longClickable="false"
app:srcCompat="#drawable/arrow_left" />
<TextView
android:id="#+id/tvBreakTime"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="10"
android:textColor="#color/white"
android:textSize="24sp" />
<ImageView
android:id="#+id/ivRight"
android:layout_width="56dp"
android:layout_height="56dp"
android:layout_weight="1"
android:clickable="true"
android:longClickable="false"
app:srcCompat="#drawable/arrow_right" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
As a side note, your viewInflation logic is wrong and currently you aren't recycling the views, so make the following amendments in your SubtaskAdapter class
public SubtaskAdapter(Context context, ArrayList<subtask> list) {
//since your are using custom view,pass zero and inflate the custom view by overriding getview
super(context, 0 , list);
this.context = context;
this.values = list;
}
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
//check if its null, if so inflate it, else simply reuse it
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.subtask_item, parent, false);
}
//use convertView to refer the childviews to populate it with data
TextView tvSubtaskName = convertView.findViewById(R.id.tvSubtaskName);
ImageView ivPri = convertView.findViewById(R.id.ivPri);
ImageView ivTime = convertView.findViewById(R.id.ivTime);
tvSubtaskName.setText(values.get(position).getSubtaskName());
if (values.get(position).isPriHigh())
{
ivPri.setImageResource(R.drawable.priority_high);
}
else if (values.get(position).isPriMed())
{
ivPri.setImageResource(R.drawable.priority_med);
}
else if (values.get(position).isPriLow())
{
ivPri.setImageResource(R.drawable.priority_low);
}
if (values.get(position).isTimeMore())
{
ivTime.setImageResource(R.drawable.time_symbol_more);
}
else if (values.get(position).isTimeMed())
{
ivTime.setImageResource(R.drawable.time_symbol_med);
}
else if (values.get(position).isTimeLess())
{
ivTime.setImageResource(R.drawable.time_symbol_less);
}
//return the view you inflated
return convertView;
}
//to keep adding the new subtasks try the following
public addANewSubTask(subtask newSubTask){
ArrayList<subtask> newvalues = new ArrayList<subtask>(this.values);
newvalues.add(newSubTask);
this.values = newvalues
notifyDataSetChanged()
}
make the following amedements in onActivityResult
subtask subtask = new subtask(subtaskName, priHigh, priMed, priLow, timeMore, timeMed, timeLess);
adapter.addANewSubTask(subtask)
There are many issues
I would suggest to initialise adapter at start of your code and then use adapter.notifyDataSetChanged(); to populate new data.
public class subtask, If you are using Java, your class names are not consistent with java standard programming style. Try renaming it to SubTask.
You can show more entries by overriding the default getCount method
#Override public int getCount() { return values.size(); }
The main problem in your code is
if (resultCode == ENTER_SUBTASK)
{
if (resultCode == RESULT_OK)
You are using resultCode for both, You might need to change
resultCode == ENTER_SUBTASK
to
requestCode == ENTER_SUBTASK
Further information can be found at
Getting a result from an activity
I'm having problems getting this view just to show up. When I go to the screen that should have the view nothing happens in the view Here are the relevant files:
CreateTimerActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_timer);
final Context context = this;
mVisible = true;
mControlsView = findViewById(R.id.create_timer_content_controls);
mContentView = findViewById(R.id.create_timer_content);
// Set up the user interaction to manually show or hide the system UI.
mContentView.setOnClickListener((View view) -> {
toggle();
});
/*XmlPullParser parser = getResources().getXml(R.id.view_tim);
AttributeSet attributes = Xml.asAttributeSet(parser);*/
final TableLayout tableLayout = (TableLayout) findViewById(R.id.create_timer_table);
TimerFormView timerFormView = new TimerFormView(context, tableLayout);
timerFormView.initializeComponents();
}
TimerFormView.java
public class TimerFormView extends TableLayout {
private Context context;
private final ContentValues timerValues;
private final ContentValues timerSegmentValues;
private final TableLayout tableLayout;
public TimerFormView(Context context, TableLayout tableLayout) {
this(context, null, tableLayout);
}
public TimerFormView(Context context, AttributeSet attrs, TableLayout tableLayout) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.TimerFormView, 0, 0);
String titleText = "Hello";
#SuppressWarnings("ResourceAsColor")
int valueColor = a.getColor(0,
android.R.color.holo_blue_light);
a.recycle();
this.context = context;
this.tableLayout = tableLayout;
TimerDatabase timerDatabase = new TimerDatabase(context);
SQLiteDatabase databaseHelper = timerDatabase.getWritableDatabase();
timerValues = new ContentValues();
timerValues.put(TimerDatabase.TimerEntry.COLUMN_NAME_TIMER_NAME, "");
timerSegmentValues = new ContentValues();
}
public TimerFormView(Context context, AttributeSet attrs)
{
this(context, attrs, null);
}
public void initializeComponents() {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.view_timer_form, this, true);
final TextView timerNameTextView = (TextView) findViewById(R.id.timerNameTxt);
timerNameTextView.setSingleLine(true);
InputFilter[] filterArrayTimerName = new InputFilter[1];
filterArrayTimerName[0] = new InputFilter.LengthFilter(32);
timerNameTextView.setFilters(filterArrayTimerName);
final Button saveTimerBtn = (Button) findViewById(R.id.saveTimerBtn);
saveTimerBtn.setEnabled(false);
saveTimerBtn.setOnClickListener((View v) -> {
timerValues.put(TimerDatabase.TimerEntry.COLUMN_NAME_TIMER_NAME, timerNameTextView.getText().toString());
});
// Enable the timer to be saved once text is entered
TextWatcher timerNameTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s){
if(s.length() > 0) {
saveTimerBtn.setEnabled(true);
} else {
saveTimerBtn.setEnabled(false);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){
// you can check for enter key here
}
public void onTextChanged (CharSequence s, int start, int before,int count) {
}
};
EditText timerNameEditText = (EditText) findViewById(R.id.timerNameTxt);
timerNameEditText.addTextChangedListener(timerNameTextWatcher);
// Segments
final TextView segmentNameTextView = (TextView) findViewById(R.id.segmentNameTxt);
segmentNameTextView.setSingleLine(true);
InputFilter[] filterArraySegmentName = new InputFilter[1];
filterArraySegmentName[0] = new InputFilter.LengthFilter(32);
segmentNameTextView.setFilters(filterArraySegmentName);
Button addSegmentBtn = (Button) findViewById(R.id.addSegmentBtn);
addSegmentBtn.setEnabled(false);
addSegmentBtn.setOnClickListener((View v) -> {
// Content for the new segment
TableRow segmentTableRow = new TableRow(context);
segmentNameTextView.setText(segmentNameTextView.getText());
segmentTableRow.addView(segmentNameTextView);
tableLayout.addView(segmentTableRow);
timerSegmentValues.put(TimerDatabase.TimerSegment.COLUMN_NAME_SEGMENT_NAME, segmentNameTextView.getText().toString());
});
TextWatcher segmentNameTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s){
if(s.length() > 0) {
saveTimerBtn.setEnabled(true);
} else {
saveTimerBtn.setEnabled(false);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){
// you can check for enter key here
}
public void onTextChanged (CharSequence s, int start, int before,int count) {
}
};
EditText segmentNameEditText = (EditText) findViewById(R.id.segmentNameTxt);
segmentNameEditText.addTextChangedListener(segmentNameTextWatcher);
EditText segmentDurationEditText = (EditText) findViewById(R.id.segmentDurationTxt);
//segmentDurationEditText.addTextChangedListener(segmentTextWatcher);
EditText segmentRepeatEditText = (EditText) findViewById(R.id.segmentRepeatTxt);
//segmentRepeatEditText.addTextChangedListener(segmentTextWatcher);
setVisibility(View.VISIBLE);
super.layout(50, 50, 50, 50);
setOrientation(LinearLayout.HORIZONTAL);
setGravity(Gravity.CENTER_VERTICAL);
}
}
view_timer_form.xml
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="400dp" android:layout_height="400dp">
<TableRow android:layout_width="400dp" android:layout_height="400dp">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Create Timer"
android:id="#+id/createTimerLbl" />
</TableRow>
<TableRow android:layout_width="match_parent" android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Timer Name"
android:id="#+id/timerNameLbl"
android:gravity="top" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/timerNameTxt"
android:layout_column="1" />
</TableRow>
<TableRow android:layout_width="match_parent" android:layout_height="wrap_content" android:id="#+id/addSegmentNameRow">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Segment Name"
android:id="#+id/segmentNameLbl"
android:gravity="top" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/segmentNameTxt"
android:layout_column="1" />
</TableRow>
<TableRow android:layout_width="match_parent" android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Duration"
android:id="#+id/segmentDurationLbl"
android:gravity="top" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/segmentDurationTxt"
android:inputType="number"
android:layout_column="1" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Seconds"
android:id="#+id/durationSecondsLbl"
android:gravity="top" />
</TableRow>
<TableRow android:layout_width="match_parent" android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Repeat"
android:id="#+id/segmentRepeatLbl"
android:gravity="top" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/segmentRepeatTxt"
android:inputType="number"
android:layout_column="1" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Times"
android:id="#+id/segmentRepeatTimesLbl"
android:gravity="top" />
</TableRow>
<TableRow android:layout_width="match_parent" android:layout_height="wrap_content" android:id="#+id/addSegmentBtnRow">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Segment"
android:id="#+id/addSegmentBtn" />
</TableRow>
<TableRow android:layout_width="match_parent" android:layout_height="wrap_content">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save Timer"
android:id="#+id/saveTimerBtn" />
</TableRow>
</TableLayout>
activity_create_timer.xml
<FrameLayout 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="#0099cc"
tools:context="com.example.timer.CreateTimerActivity">
<TextView android:id="#+id/create_timer_content" android:layout_width="match_parent"
android:layout_height="match_parent" android:keepScreenOn="true" android:textColor="#33b5e5"
android:textStyle="bold" android:textSize="50sp" android:gravity="center"
android:text="" />
<!-- This FrameLayout insets its children based on system windows using
android:fitsSystemWindows. -->
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<LinearLayout
android:id="#+id/create_timer_content_controls"
style="?metaButtonBarStyle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="20dp"
tools:ignore="UselessParent">
<com.example.timer.views.TimerFormView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/create_timer_table">
</com.example.timer.views.TimerFormView>
</LinearLayout>
</FrameLayout>
</FrameLayout>
I had such issue and I solved it in this ways...
Don't call any instance of customView or even static vars from activity.
only define constructor with (Context, Attributes)
and initialize everything you want inside customView class.
Good luck
I have an adapter class which loads items dynamically and shows them in a RecyclerView. My problem is that when I swipe up and down the recycler view the images get mixed and are shown in wrong positions (i.e. in other item's view).
For example, I have an item X and another item Y. Now when I swipe up and down the image which was to be shown in item Y get shown in item X and the same happens with other attributes.
Here is my adapter class:
public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.NewsViewHolder> {
private DatabaseReference refDNewsTable= FirebaseDatabase.getInstance().getReference().child("news_feeds");
private StorageReference refStorage = FirebaseStorage.getInstance().getReferenceFromUrl("firebase_url_comes_here");
private Context mContext;
private List<NewsModel> newsList;
public class NewsViewHolder extends RecyclerView.ViewHolder {
public TextView nHeading, nDes,nDaTi;
public ImageView nImg;
public NewsViewHolder(View view) {
super(view);
nHeading = (TextView) view.findViewById(R.id.tv_newsHeadline);
nDes = (TextView) view.findViewById(R.id.tv_nDes);
nImg = (ImageView) view.findViewById(R.id.iv_nImg);
nDaTi=(TextView) view.findViewById(R.id.tv_nDaTi);
}
}
public NewsAdapter(Context mContext, List<NewsModel> newsList) {
this.mContext = mContext;
this.newsList = newsList;
}
#Override
public NewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.news_model, parent, false);
return new NewsViewHolder(itemView);
}
#Override
public void onBindViewHolder(final NewsViewHolder holder, int position) {
NewsModel news = newsList.get(position);
holder.nHeading.setText(news.getnHeading());
if(news.hasDes()) {
holder.nDes.setText(news.getnDes());
}else{
holder.nDes.setVisibility(View.GONE);
}
if(news.hasImg()){
// Reference to an image file in Firebase Storage
StorageReference imgReference =refStorage.child(news.getnId());
// Load the image using Glide
Glide.with(mContext)
.using(new FirebaseImageLoader())
.load(imgReference)
.into(holder.nImg);
}else{
holder.nImg.setVisibility(View.GONE);
}
holder.nDaTi.setText(news.getnDaTi());
}
public void downloadFile(final NewsViewHolder holder){
try {
final File localFile = File.createTempFile("images", "jpg");
refStorage.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Bitmap bitmap = BitmapFactory.decodeFile(localFile.getAbsolutePath());
holder.nImg.setImageBitmap(bitmap);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
} catch (IOException e ) {}
}
#Override
public int getItemCount() {
return newsList.size();
}
}
And this is my news_model.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:padding="10dp"
android:layout_margin="4dp"
card_view:cardPreventCornerOverlap="true"
card_view:cardElevation="16dp"
android:layout_height="wrap_content"
android:id="#+id/card_view"
android:layout_gravity="center"
card_view:cardCornerRadius="0dp">
<LinearLayout
android:orientation="vertical"
android:background="#color/cBgNews"
android:padding="0dp"
android:gravity="center_horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:padding="10dp"
card_view:cardElevation="6dp"
card_view:cardBackgroundColor="#color/cNewsHeadline"
android:layout_height="wrap_content"
android:layout_marginTop="0dp"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="0dp"
android:id="#+id/card_des"
android:layout_gravity="center"
card_view:cardCornerRadius="0dp">
<TextView
android:text="TextView"
android:textSize="17sp"
android:textStyle="normal"
android:padding="10dp"
android:maxLines="3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/cWhite"
android:gravity="start"
android:layout_margin="0dp"
android:id="#+id/tv_newsHeadline" />
</android.support.v7.widget.CardView>
<LinearLayout
android:orientation="vertical"
android:gravity="center_horizontal"
android:background="#0000"
android:paddingEnd="6dp"
android:paddingStart="6dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="wrap_content"
android:layout_marginBottom="0dp"
android:layout_height="wrap_content"
android:maxHeight="300dp"
app:srcCompat="#mipmap/ic_launcher"
android:scaleType="fitCenter"
android:layout_gravity="center_horizontal"
android:id="#+id/iv_nImg" />
<TextView
android:text="Description..."
android:maxLines="8"
android:textSize="16sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="end"
android:padding="10dp"
android:textColor="#color/cBlack"
android:id="#+id/tv_nDes" />
<TextView
android:text="Date and Time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="10sp"
android:textColor="#999999"
android:gravity="end"
android:id="#+id/tv_nDaTi" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
NOTE: I am using firebase to receive the content directly and haven't created any kind of database in my app yet. i.e. it loads data every time it needs it directly in adapter class.
I've used SwipeDeck2, I set every thing and it is working, but I have one issue that is I can not set OnClickListener correctly on one of the views in card I have layout as
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/root_cv"
style="#style/CardViewStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="24dp"
android:elevation="5dp"
app:cardCornerRadius="7dp"
android:layout_gravity="top">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<org.team.asl.me_c.ui.DynamicHeightImageView
android:id="#+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="88dp"
android:scaleType="fitCenter"
app:heightRatio="1.0"
android:background="#color/grey_white_1000"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:orientation="vertical"
android:gravity="center_vertical"
android:padding="16dp"
android:background="#color/indigo_A200"
android:layout_gravity="bottom">
<TextView android:layout_marginTop="-15dp"
android:id="#+id/display_name_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#android:color/white"
android:fontFamily="sans-serif"
android:textStyle="bold"
android:textSize="22sp"/>
<TextView
android:id="#+id/username_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#android:color/white"
android:fontFamily="sans-serif"
android:textSize="16sp"/>
</LinearLayout>
</FrameLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipChildren="true">
<ImageButton
android:id="#+id/btnLike"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_gravity="top|right"
android:background="#android:color/transparent"
android:src="#drawable/ic_heart_outline_grey" />
<TextView
android:id="#+id/like_tv"
android:layout_width="120dp"
android:background="#drawable/shape_bg_green_rounded_rect"
android:layout_height="56dp"
android:gravity="center"
android:textSize="32sp"
android:text="LIKE"
android:textStyle="bold"
android:alpha="0"
android:layout_marginTop="32dp"
android:layout_marginBottom="32dp"
android:layout_marginLeft="24dp"
android:textColor="#android:color/holo_green_light"/>
<TextView
android:id="#+id/nope_tv"
android:layout_gravity="right"
android:layout_width="120dp"
android:background="#drawable/shape_bg_red_rounded_rect"
android:layout_height="56dp"
android:textSize="32sp"
android:gravity="center"
android:textStyle="bold"
android:text="NOPE"
android:alpha="0"
android:layout_marginTop="32dp"
android:layout_marginBottom="32dp"
android:layout_marginRight="24dp"
android:textColor="#android:color/holo_red_light"/>
</FrameLayout>
</FrameLayout>
</android.support.v7.widget.CardView>
and the adapter as
public class SwipeDeckAdapter extends BaseAdapter {
private List<String> data;
private Context context;
private int countLike = 0;
private ImageButton btnLike;
//private View.OnClickListener onClickListener;
public SwipeDeckAdapter(List<String> data, Context context) {
this.data = data;
this.context = context;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null){
LayoutInflater inflater = LayoutInflater.from(context);
// normally use a viewholder
v = inflater.inflate(R.layout.product_card, parent, false);
}
((TextView) v.findViewById(R.id.display_name_tv)).setText(data.get(position));
btnLike = (ImageButton) v.findViewById(R.id.btnLike);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = (String)getItem(position);
Log.e("MainActivity", item);
}
});
btnLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
countLike ++;
Log.e("LIKE_CONT", " is " + countLike);
btnLike.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_heart_red));
Toast.makeText(context, "Clicked at index ", Toast.LENGTH_SHORT).show();
}
});
return v;
}
}
I want to add click listener on btnLike and want to change the image resource in method
btnLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
countLike ++;
Log.e("LIKE_CONT", " is " + countLike);
btnLike.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_heart_red));
Toast.makeText(context, "Clicked at index ", Toast.LENGTH_SHORT).show();
}
});
but result is
means the image resource of btnLike is not changed in current card but as I shuffle cards and see on the other card the image resource of btnLike is changed any suggestions how to see that bit of code so that it can work properly...
Problem: Trying to output the description of the selected listview. My code is below, and I also have an example of what my listview looks like as well as the code that creates it. I have a custom listview that shows three values, when I click the 2nd line (3/12/04 Gas $60.00) I want it to output the description ("Gas").
The onItemClick is where my issue is in ItemMenuActivity.
Thanks for your help and time!
Example Data in listview:
3/12/04 New Shoes $50.00
3/12/04 Gas $60.00
3/12/04 Food $10.00
ItemMenuActivity.java
public class ItemMenuActivity extends Activity implements AdapterView.OnItemClickListener
{
String accountName;
ArrayList<Item> item_details;
DatabaseHandler database;
ListView itemView;
private EditText dateEditText, costEditText, desEditText;
private Spinner categorySpinner;
private Button btnAddItem, btnCancel;
private boolean errlvl;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.item_menu_layout);
// Initiate Database
database = new DatabaseHandler(getApplicationContext());
// Initiate/configure ListView
itemView = (ListView)findViewById(R.id.itemListView);
itemView.setOnItemClickListener(this);
Bundle bundle = getIntent().getExtras();
String account_name = bundle.getString("AccountName");
setTitle(account_name);
accountName = account_name;
displaySpecificItemListView(accountName);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
//TextView editTextDescription = ((TextView)view.findViewById(R.id.editTextDescription));
//String temp = editTextDescription.getText().toString();
//Toast.makeText(this, temp, Toast.LENGTH_LONG).show();
}
}
add_item_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/addItemLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:padding="10dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/textViewDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="#string/purchDateTitle"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<EditText
android:id="#+id/editTextDate"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textAppearance="?android:attr/textAppearanceMedium"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<EditText
android:id="#+id/editTextDescription"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:hint="Enter Item Description"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="$ "
android:textSize="20dp"/>
<EditText
android:id="#+id/editTextCost"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:hint="Enter Total Cost"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Spinner
android:id="#+id/categorySelectSpinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:orientation="horizontal">
<Button
android:id="#+id/btnAddItem"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Add" />
<Button
android:id="#+id/btnCancelItem"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Cancel" />
</LinearLayout>
</LinearLayout>
ItemListViewBaseAdapter.java
public class ItemListViewBaseAdapter extends BaseAdapter
{
private ArrayList<Item> _data;
Context _c;
ItemListViewBaseAdapter (ArrayList<Item> data, Context c)
{
_data = data;
_c = c;
}
public int getCount()
{
// TODO Auto generated method stub
return _data.size();
}
public Object getItem(int position)
{
// TODO Auto generated method stub
return _data.get(position);
}
public long getItemId(int position)
{
// TODO Auto generated method stub
return position;
}
public View getView (int position, View convertView, ViewGroup parent)
{
// TODO Auto generate method stub
View v = convertView;
if (v == null)
{
LayoutInflater vi = (LayoutInflater)_c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.custom_item_listview_layout, null);
}
TextView itemDate = (TextView)v.findViewById(R.id.dateTextView);
TextView itemDescription = (TextView)v.findViewById(R.id.descriptionTextView);
TextView itemAmount = (TextView)v.findViewById(R.id.amountTextView);
Item accMsg = _data.get(position);
itemDate.setText(accMsg.entry_date);
itemDescription.setText(accMsg.item_description);
//NumberFormat format
if(accMsg.item_price > 0)
{
String myString = String.format("%.2f", accMsg.item_price);
String FormattedString = "$"+myString;
itemAmount.setText(FormattedString);
}
else
{
double temp = Math.abs(accMsg.item_price);
String myString = String.format("%.2f", temp);
String FormattedString = "-$"+myString;
itemAmount.setText(FormattedString);
itemAmount.setTextColor(Color.parseColor("#088A08"));
}
return v;
}
}
item_menu_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="#+id/itemListView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:dividerHeight="0.1dp"
android:divider="#81A594"
android:layout_below="#+id/dateTitle"/>
</RelativeLayout>
In your onItemClick() method you're doing
TextView editTextDescription = ((TextView)view.findViewById(R.id.editTextDescription));
to get your TextView. This matches the XML you posted (add_item_layout.xml), but your adapter code tells a different story.
In your adapter, for new rows you are inflating custom_item_listview_layout and your "description" TextView ID is R.id.descriptionTextView.
So if you make this edit in onItemClick(), it should solve your problem:
TextView editTextDescription = ((TextView)view.findViewById(R.id.descriptionTextView));