How to add many TextViews to GridLayout in Java? - java

My activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
android:id="#+id/mainWindow"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
>
<GridLayout
android:id="#+id/gridLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:rowCount="2"
android:columnCount="2"
android:useDefaultMargins="true"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_rowWeight="1"
android:layout_columnWeight="1"
android:layout_row="0"
android:layout_column="0"
android:background="#drawable/shape"
android:gravity="center"
android:text="Hallo"
/>
</GridLayout>
</android.support.constraint.ConstraintLayout>
How I can add many of this TextFields to the GridLayout in Java.
I tried:
package com.example.sudokusolver;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.GridLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridLayout.LayoutParams lp= new GridLayout.LayoutParams();
lp.width= GridLayout.LayoutParams.MATCH_PARENT;
lp.height= GridLayout.LayoutParams.MATCH_PARENT;
lp.columnSpec= GridLayout.spec(GridLayout.UNDEFINED, 1f);
lp.rowSpec= GridLayout.spec(GridLayout.UNDEFINED, 1f);
TextView textView= new TextView(this);
textView.setBackgroundResource(R.drawable.shape);
textView.setGravity(Gravity.CENTER);
textView.setText("Hallo");
GridLayout grid= findViewById(R.id.gridLayout);
grid.addView(textView);
grid.addView(textView);
}
}
But if i add so more then 1 TextView the error come:
The specified child already has a parent. You must call removeView() on the child's parent first. How I can do this?

You can add a custom view GridChild to your GridLayout which can contain multiple TextViews like this
<?xml version="1.0" encoding="utf-8"?>
<GridLayout
android:id="#+id/gridLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:rowCount="1"
android:columnCount="2"
android:useDefaultMargins="true">
<com.example.customview.GridChild/>
</GridLayout>
and your GridChild class
package com.example.customview;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.LinearLayout;
import android.widget.TextView;
public class GridChild extends LinearLayout {
private TextView text1;
private TextView text2;
public MyView(Context context) {
super(context);
init();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
inflate(getContext(), R.layout.layout_ll, this);
this.text1 = (TextView)findViewById(R.id.textview1);
this.text2 = (TextView)findViewById(R.id.textview2);
}
}

Related

Problems sub-classing a custom ImageView

I am writing an app where I need to create a custom ImageView (in order to override its onDraw). After failing to do that for a couple of weeks I created a minimal, reproducible example which captures the problem. Here is the code:
package com.nzeldes.mytestapp;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.util.AttributeSet;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
CustomImageView myImageView;
Bitmap myBitmap;
class CustomImageView extends androidx.appcompat.widget.AppCompatImageView {
public CustomImageView(#NonNull Context context) {
super(context);
}
public CustomImageView(#NonNull Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
}
public CustomImageView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int displaywidth = Resources.getSystem().getDisplayMetrics().widthPixels;
myBitmap = Bitmap.createBitmap(displaywidth, displaywidth, Bitmap.Config.ARGB_8888);
myBitmap.eraseColor(Color.BLACK);
myImageView = findViewById(R.id.imageView); // Get a reference to the ImageView
myImageView.setImageBitmap(myBitmap); // Associate the bitmap to the ImageView
}
}
and the XML layout:
*<?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"
tools:context=".MainActivity">
<ImageView
android:id="#+id/imageView"
android:layout_width="403dp"
android:layout_height="366dp"
android:layout_marginTop="72dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_launcher_background" />
</androidx.constraintlayout.widget.ConstraintLayout>*
However, in the source window I get a “Unexpected implicit cast to CustomImageView: layout tag was ImageView” warning on myImageView = findViewById(R.id.imageView);
And if I try to run the app it crashes with this error from Logcat:
java.lang.ClassCastException: androidx.appcompat.widget.AppCompatImageView cannot be cast to com.nzeldes.mytestapp.MainActivity$CustomImageView
I admit to being new to Android (putting the lockdown times to some use learning something new!)... any help will be most appreciated.
For inner classes the syntax becomes:
<view class="{package}.{ParentClass}${innerClass}"
Please change your layout like the code below
<?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"
tools:context=".MainActivity">
<view class="com.nzeldes.mytestapp.MainActivity$CustomImageView"
android:id="#+id/imageView"
android:layout_width="403dp"
android:layout_height="366dp"
android:layout_marginTop="72dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/ic_launcher_background" />
</androidx.constraintlayout.widget.ConstraintLayout>

ListView only shows the first item from the arraylist

Previously I had crash issues due to the wrong reference to the resource files. Fixed that issue and updated this thread with the logical error that I am getting.
I am new to android and currently learning custom classes and adapter. While working I am facing a problem which is the listview shows the first arraylist item only.
I have attached the codes of the required files as well.
Working Activity
package np.com.shresthakiran.tourswoniga;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class KhowpaActivity extends AppCompatActivity {
ListView lvHeritageList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview_heritage);
lvHeritageList = findViewById(R.id.lvHeritage);
ArrayList<Heritages> heritageAryList = new ArrayList<>();
heritageAryList.add(new Heritages(R.drawable.ic_launcher_background,"Ngatapol", "Taumadi"));
heritageAryList.add(new Heritages(R.drawable.ic_launcher_foreground, "Dattatreya", "Taumadi"));
heritageAryList.add(new Heritages(R.drawable.ic_launcher_foreground, "Lu dhwakha", "Lyaaku"));
heritageAryList.add(new Heritages(R.drawable.ic_launcher_foreground, "55 jhyale Durbar", "Lyaaku"));
heritageAryList.add(new Heritages(R.drawable.ic_launcher_foreground, "Taleju Bhawani", "Lyaaku"));
HeritageAdapter heritageAdapter = new HeritageAdapter(KhowpaActivity.this, R.layout.heritages_row, heritageAryList);
lvHeritageList.setAdapter(heritageAdapter);
}
}
Custom Adapter
package np.com.shresthakiran.tourswoniga;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import java.util.ArrayList;
public class HeritageAdapter extends ArrayAdapter<Heritages> {
private Context mContext;
private int mResource;
public HeritageAdapter(#NonNull Context context, int resource, #NonNull ArrayList<Heritages> objects) {
super(context, resource, objects);
this.mContext = context;
this.mResource = resource;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater layoutInflater =LayoutInflater.from(mContext);
convertView = layoutInflater.inflate(mResource, parent, false);
ImageView ivHeritageImage = convertView.findViewById(R.id.ivHeritage);
TextView tvHeritageName = convertView.findViewById(R.id.tvHeritageName);
TextView tvHeritageAddress = convertView.findViewById(R.id.tvHeritageAddress);
ivHeritageImage.setImageResource(getItem(position).getmImageResourceId());
tvHeritageName.setText(getItem(position).getmHeritageName());
tvHeritageAddress.setText(getItem(position).getmHeritageAddress());
return convertView;
}
}
Object Class
package np.com.shresthakiran.tourswoniga;
public class Heritages {
private int mImageResourceId;
private String mHeritageName;
private String mHeritageAddress;
public Heritages(int heritageImageResourceId, String heritageName, String heritageAddress) {
this.mImageResourceId = heritageImageResourceId;
this.mHeritageName = heritageName;
this.mHeritageAddress = heritageAddress;
}
public int getmImageResourceId() {
return mImageResourceId;
}
public String getmHeritageName() {
return mHeritageName;
}
public String getmHeritageAddress() {
return mHeritageAddress;
}
}
ListView XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="100dp"
android:minHeight="100dp">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/lvHeritage">
</ListView>
</RelativeLayout>
List Row XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="100"
android:layout_margin="10dp">
<ImageView
android:id="#+id/ivHeritage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="33.33"
android:padding="2dp"
android:text="Ngatapol"
android:layout_marginTop="7dp"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:id="#+id/llHeritageInfo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="66.66"
android:padding="8dp" >
<TextView
android:id="#+id/tvHeritageName"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:textSize="18sp"
android:textStyle="bold"
android:text="Ngatapol"
android:textAppearance="?android:textAppearanceMedium"
android:padding="2dp"/>
<TextView
android:id="#+id/tvHeritageAddress"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:textSize="18sp"
android:text="Taumadi"
android:padding="2dp"/>
</LinearLayout>
</LinearLayout>
listview shows the first item only is because you have set height in heritages_row layout to match_parent which will cover the whole screen height and for the next item, you've to scroll down even if the content of the first item is not covering the whole height.
To make each row to only cover the content its displaying, use wrap_content instead of match_parent.

restrict a custom view in a relative layout

I am new to android and I am a bit stuck. I am trying to create a simple drawing app which shows an example on the top of the page and a square space for it in below it. Aim is to display a letter and a kid needs to practice in replicating it.
I have troubles including the drawing class in the layout which needs to restrict its boundaries.
this is the main layout
<?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"
tools:context=".MainActivity">
<TextView
android:id="#+id/exampleText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.constraintlayout.widget.ConstraintLayout
enter code here` android:id="#+id/drawingBoard"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/exampleText">
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
this is the PaintView class
import android.app.ActionBar;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
public class PaintView extends View {
public ViewGroup.LayoutParams param;
private Path path = new Path();
private Paint brush = new Paint();
public PaintView(MainActivity context) {
super(context);
brush.setAntiAlias(true);
brush.setColor(Color.RED);
brush.setStyle(Paint.Style.STROKE);
brush.setStrokeJoin(Paint.Join.ROUND);
brush.setStrokeWidth(8f);
param = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float pointX = event.getX();
float pointY = event.getY();
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
path.moveTo(pointX,pointY);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(pointX,pointY);
break;
default:
return false;
}
postInvalidate();
return false;
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path,brush);
}
this is how it is called in the Main Activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PaintView paintView = new PaintView(this);
setContentView(paintView);
}
I need to fit the drawing board into the "drawingBoard".
It is not necessary the right approach, but this is as far as I got.
Thanks in advance
Attach the customview to a fragment.
This is a completely different approach so you will have to make a lot of changes to your code.
The other approach would be adding the view programmatically to the ConstraintLayout.
In MainActivity,
protected void onCreate(Bundle savedInstanceStatee) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//remove those lines.
/*
PaintView paintView = new PaintView(this);
setContentView(paintView);*/
ConstraintLayout parentLayout = (ConstraintLayout)findViewById(R.id.drawingBoard);
ConstraintSet set = new ConstraintSet();
PaintView paintView = new PaintView(this);
// set view id, else getId() returns -1
paintView.setId(View.generateViewId());
layout.addView(paintView, 0);
set.clone(parentLayout);
// connect start and end point of views, in this
case top of child to top of parent.
set.connect(paintView.getId(),
ConstraintSet.TOP,parentLayout.getId(),
ConstraintSet.TOP, 60);
// ... similarly add other constraints
set.applyTo(parentLayout);
}
In the activity you are overwriting the content view with just the paint view:
setContentView(paintView);
Remove that line.
Add the PaintView in XML instead:
<?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"
tools:context=".MainActivity">
<TextView
android:id="#+id/exampleText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<!-- TODO: Replace with your package name -->
<com.example.PaintView
android:id="#+id/drawingBoard"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/exampleText" />
</androidx.constraintlayout.widget.ConstraintLayout>
With this approach you have to inflate the custom view in its constructors:
public class PaintView extends ConstraintLayout {
public PaintView(#NonNull Context context) {
super(context);
init();
}
public PaintView(#NonNull Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public PaintView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
public PaintView(#NonNull Context context, #Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init();
}
public void init() {
inflate(getContext(), R.layout.layout_product_item, this);
}
}
To interact with the PaintView from the activity code you can do:
PaintView paintView = (PaintView) findViewById(R.id.drawingBoard);

Android:Onclick not finding onclick method

I am attempting to make a custom view that uses buttons, however, the android:Onclick for the two buttons cause the app to crash. The ClickListeners don't work either.
The error I am getting from running the debug tool is :
java.lang.IllegalStateException: Could not find a method addMenu(View) in the activity class com.android.tools.fd.runtime.BootstrapApplication for onClick handler on view class android.widget.Button with id 'increase'
This is My java code :
public class MenuItems extends LinearLayout{
private View plusButton;
private View negateButton;
private EditText priceBox;
private TextView total;
private TextView name;
private int totalItems;
private double totalPrice;
private double price;
public MenuItems(Context context) {
super(context);
init();
}
public MenuItems(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public void init()
{
LayoutInflater inflater=LayoutInflater.from(getContext());
inflater.inflate(R.layout.menu_item,this);
plusButton=findViewById(R.id.increase);
negateButton=findViewById(R.id.decrease);
total=(TextView)findViewById(R.id.total);
name=(EditText)findViewById(R.id.ItemName);
priceBox=(EditText)findViewById(R.id.Price) ;
total.setText("5");
negateButton.setBackgroundColor(Color.RED);
plusButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
plusButton.setBackgroundColor(Color.RED);
increase();
}
});
negateButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
decrease();
negateButton.setBackgroundColor(Color.RED);
}
});
price=0;
totalItems=0;
upDateTotal();
String pString=priceBox.getText().toString();
price=Double.parseDouble(pString);
}
public void increase(View view)
{
totalItems++;
upDateTotal();
System.out.println("plus");
plusButton.setBackgroundColor(Color.RED);
}
public void decrease(View v)
{
if(totalItems>0)
totalItems--;
upDateTotal();
System.out.println("minus");
}
This is all of my xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/menu_items"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.mohs.joey.seniorproject.MenuItems">
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/ItemName"
android:layout_weight="1"
android:textColor="#color/colorAccent"
android:text="name" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="#+id/Price"
android:textColor="#color/colorAccent"
android:hint="Price"
android:shadowColor="#color/colorAccent"
android:text="0.00" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:text="-"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:id="#+id/decrease"
android:layout_weight="1"
android:backgroundTint="#color/colorAccent"
android:onClick="increase"/>
<TextView
android:text="Amount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/total"
android:layout_weight="1"
android:textColor="#color/colorAccent" />
<Button
android:text="+"
android:layout_width="50dp"
android:layout_height="wrap_content"
android:id="#+id/increase"
android:layout_weight="1"
android:backgroundTint="#color/colorAccent"
android:elevation="0dp"
android:onClick="increase" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
I access MenuItems in this Method in a separate class :
public void addMenu(View view)
{
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.menu_item, null);
v.setId(menu);
ViewGroup insertPoint = (ViewGroup) findViewById(R.id.backLayer);
insertPoint.addView(v, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
menu++;
}
This is my new main activity:
package com.mohs.joey.seniorproject;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;
public class ConcessionMenus extends AppCompatActivity {
int menu=0;
private View plusButton;
private View negateButton;
private EditText priceBox;
private TextView total;
private TextView name;
private int totalItems;
private double totalPrice;
private double price;
PopupWindow popup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_concession_menus);
plusButton=findViewById(R.id.increase);
negateButton=findViewById(R.id.decrease);
total=(TextView)findViewById(R.id.total);
name=(EditText)findViewById(R.id.ItemName);
priceBox=(EditText)findViewById(R.id.Price) ;
// TextView totalPrice=(TextView)findViewById(R.id.totalPrice);
}
public void addMenu(View view)
{
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View vw = vi.inflate(R.layout.menu_item, null);
vw.setId(menu);
ViewGroup insertPoint = (ViewGroup) findViewById(R.id.backLayer);
insertPoint.addView(vw, 0, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
menu++;
}
public Intent newIntent()
{
Intent intent=new Intent(this,Menu.class);
return intent;
}
public void increase(View v)
{
totalItems++;
upDateTotal();
System.out.println("plus");
plusButton.setBackgroundColor(Color.RED);
}
public void decrease(View v)
{
if(totalItems>0)
totalItems--;
upDateTotal();
System.out.println("minus");
}
public void upDateTotal()
{
total.setText(""+totalItems);
totalPrice=price*totalItems;
}
public double totalPrice()
{
return totalPrice;
}
}
Any help would be appreciated.
The problem is when the button want to perform the action when you click on it , it should be able to find the method increase() in your MainActivity class , since the method increase() is on an other class , the button will never find the method and they will crash because you set the your layout xml to your main activity not for the class MenuItem , to fix that just move these to methods to your MainActivity class
OR
Pass a reference of your buttons to the class MenuItems and do what you want there
PS : the ids can be found by typing R.id , but you cannot work with these id since you set the content view to your MainActivity

listview does not update with notifydatasetchanged() call

My Android listview does not update with notifydatasetchanged() call.
The Main Code Activity:
package com.example.jokesbook;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.jokesbook.MESSAGE";
CustomAdapter Adapter;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JokeDB.jokesList = new ArrayList<Joke>();
JokeDB.jokesList.add(new Joke("DDD"));
lv = (ListView)findViewById(android.R.id.list);
Adapter= new CustomAdapter(MainActivity.this, R.layout.joke_list_item, JokeDB.jokesList);
lv.setAdapter(Adapter);
}//onCreate
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
Log.d("jokesbook", "onResume ");
Adapter.notifyDataSetChanged();
}
class CustomAdapter extends ArrayAdapter<Joke>{
Context context;
int layoutResourceId;
ArrayList<Joke> data = null;
private LayoutInflater mInflater;
public CustomAdapter(Context customAdapter, int layoutResourceId, ArrayList<Joke> data) {
super(customAdapter, layoutResourceId, data);
Log.d("jokesbook", "CustomAdapter ");
this.layoutResourceId = layoutResourceId;
this.context = customAdapter;
this.data = data;
this.mInflater = LayoutInflater.from(customAdapter);
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
//item_list
convertView = mInflater.inflate(R.layout.joke_list_item, null);
holder = new ViewHolder();
//fill the views
holder.joke = (TextView) convertView.findViewById(R.id.ListTextView1);
convertView.setTag(holder);
}
else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();//
}
holder.joke.setText(data.get(position).jokeStr);
return convertView;
}
class ViewHolder {
TextView joke;
}
}
/** Called when the user clicks the Add a new joke button */
public void goNewJoke(View view) {
Intent intent = new Intent(this, New_joke.class);
startActivity(intent);
}
}
Its xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="#+id/ButtonAboveList"
android:layout_width="500dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:onClick="goNewJoke"
android:text="#string/Add_a_new_joke"/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
When adding content to JokeDB.jokesList in another activity that its code is:
package com.example.jokesbook;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class New_joke extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_joke);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.new_joke, menu);
return true;
}
public void addJoke(View view){
EditText editTextJoke= (EditText)findViewById(R.id.edit_text_jokeToAdd);
JokeDB.jokesList.add(new Joke(editTextJoke.getText().toString()));
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
and its XML is:
<LinearLayout 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="#color/green"
android:orientation="vertical"
android:paddingLeft="3dp"
android:paddingRight="3dp"
android:paddingTop="3dp"
tools:context=".New_joke" >
<EditText
android:id="#+id/edit_text_jokeToAdd"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:layout_marginBottom="40dp"
android:background="#color/white"
android:hint="#string/edit_message" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="horizontal"
tools:context=".New_joke" >
<TextView
android:id="#+id/AuthorText"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:gravity="left"
android:text="#string/Author"
android:textColor="#android:color/white"
android:textSize="25sp" />
<EditText
android:id="#+id/edit_text_Author"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:background="#color/white"
android:hint="#string/Only_letters_allowed"
android:inputType="textPersonName" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="60dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="horizontal"
tools:context=".New_joke" >
<TextView
android:id="#+id/DateText"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:gravity="left"
android:text="#string/Date"
android:textColor="#android:color/white"
android:textSize="25sp" />
<EditText
android:id="#+id/edit_text_Date"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:background="#color/white"
android:hint="#string/Only_digits_allowed"
android:inputType="number" />
</LinearLayout>
<Button
android:id="#+id/ButtonAboveList"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:onClick="addJoke"
android:text="#string/Add" />
</LinearLayout>
I cannot see the updated list in the main activity eveb though in onResume I used notifydatasetchanged() function.
Try This....
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
Log.d("jokesbook", "onResume ");
notifyDataSetChanged();
}

Categories

Resources