First I'm a beginner in Android development !
In my app, I include a library that help me to create card UI.
In this library, you have a basic layout where there is a Title, a description and a thumbnails but you can create and inflate a custom layout for having a better filled card.
What I want to do is to change the text of a TextView coming from the sub Class, which is linked to the sub Layout. But everytime I try to invoke the setText method from the MainActivity, I get a NullPointerexception.
There is my sub Class:
import it.gmariotti.cardslib.library.internal.Card;
import it.gmariotti.cardslib.library.internal.Card.OnCardClickListener;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
public class CustomCardAccueil extends Card{
public TextView TitreExtensionAccueil;
public TextView DateSortieAccueil;
public TextView NombreCarteAccueil;
public TextView DescriptionExtensionAccueil;
public TextView RareteCarteAccueil;
public TextView DetailExtensionAccueil;
public CustomCardAccueil(Context context) {
this(context, R.layout.accueil_mycard_inner_content);
}
/**
*
* #param context
* #param innerLayout
*/
public CustomCardAccueil(Context context, int innerLayout) {
super(context, innerLayout);
init();
}
/**
* Init
*/
private void init(){
//No Header
//Set a OnClickListener listener
setOnClickListener(new OnCardClickListener() {
#Override
public void onClick(Card card, View view) {
Toast.makeText(getContext(), "Click Listener card=", Toast.LENGTH_LONG).show();
}
});
}
#Override
public void setupInnerViewElements(ViewGroup parent, View view) {
TitreExtensionAccueil = (TextView) parent.findViewById(R.id.TitreExtensionAccueil);
}
}
My Layout where there is the TextView that I want to change:
<?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" >
<TextView
android:id="#+id/TitreExtensionAccueil"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:textStyle="bold"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/DateSortieAccueil"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/TitreExtensionAccueil"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/NombreCarteAccueil"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/DateSortieAccueil"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/DescriptionExtensionAccueil"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/NombreCarteAccueil"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/RareteCarteAccueil"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/DescriptionExtensionAccueil"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/DetailExtensionAccueil"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/RareteCarteAccueil"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
And there is how I try to change the content of TextView in my MainActivity, in the OnCreate:
CustomCardAccueil.TitreExtensionAccueil.setText("Test");
There is also the error I get in the logcat of the crash:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText.setText(java.lang.CharSequence)' on a null object reference
I don't understand the error because the object is initiated (correct me if I'm wrong).
Also if I try to change the text from the sub class (CustomCardAccueil), it's a success, but I need to do it through my MainActivity.
Any help is appreciated, thanks in advance !
You need to initialize the class with something like:
CustomCardAccueil myCard = new CustomCardAccueil(mContext, R.mylayout);
The context you can get from your activity class using something like MyActivity.this or getApplicationContext(). Then you can use methods such as the class' setText:
myCard.setText("blah")
Your TitreExtensionAccueil is said to be null when you are trying to set the text.
You may want to point out where are CustomCardAccueil.TitreExtensionAccueil.setText("Test"); is called for better respond to your question.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText.setText(java.lang.CharSequence)' on a null object reference
shows that you invoked setText() on a null object, so did you initialize CustomCardAccueil.TitreExtensionAccueil and how?
your problem is or you are not using the proper instance for the class CustomCardAccueil, as you declared and initialized the TextView through it, So, even you have to make an instance from the class or to make the TextView declared as static variable, but make sure you run the method called setupInnerViewElements() before trying to set the TextView value.
UPDATE:
to get the current window view through some layout:
View global_view = getWindow().getDecorView(); // use that in the MainActivity to get the view
then, pass that view to your method setupInnerViewElements() and simply create the view with it not with ViewGroup:
in your MainActivity:
CustomCardAccueil mCard = new CustomCardAccueil(getApplicationContext(), R.layout.accueil_mycard_inner_content);
mCard.setupInnerViewElements(parent, global_view);
in your setupInnerViewElements() method:
#Override
public void setupInnerViewElements(ViewGroup parent, View view) {
TitreExtensionAccueil = (TextView) view.findViewById(R.id.TitreExtensionAccueil);
}
I've found the answer by looking at the card library and his setTitle Library (I don't know why I've not thinked to this sooner !)
In my CustomCardAccueil class, I've created a String as this:
protected static String titreExtension;
Here is the getter and setter methods:
public String getTitreExtension() {
return titreExtension;
}
public static void setTitreExtension(String titre) {
titreExtension = titre;
}
Again in CustomCardAccueil, in setupInnerViewElements method, I've put this:
TitreExtensionAccueil = (TextView) view.findViewById(R.id.TitreExtensionAccueil);
TitreExtensionAccueil.setText(titreExtension);
And in my MainActivity I simply call my setter with:
CustomCardAccueil.setTitreExtension("test du setTitreExtension");
Simply as this !
Related
I'll try my best to make it clear.
I'm trying to create a scrollview of item (let's say it's a shop) which I (the user) add by my self VIA the interface of the app AND can then modify by clicking on it inside the scrollview.
For example, my main page contains a button and the list of items. When I click on it it opens a dialog which asks me informations of the item I want to add. When I finished configuring the item, I'm back on the main page and I can see the item I just added and i can click on it to modify it if I need to.
What I struggle with here is the fact, in a scrollview we have to add views. Even if I know how to do it via java, how can I add, for each new item, a clicklistener ? how do I set the id for each new view (items) considering the fact that I only can set int ids ? etc.
Does someone knows any way to do what I try to ? I'll make a very simple example of code and interfaces screenshot here in order to be very clear.
My XML MainPage : "activity_main.xml"
<?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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="#+id/popUpAddItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Your Item"
tools:ignore="MissingConstraints">
</Button>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/scrollViewItems">
<!-- this LinearLayout is an exemple of the shape/structure of an item -->
<LinearLayout
android:clickable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/protoItem">
<TextView
android:clickable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Item1 "
android:id="#+id/protoName">
</TextView>
<TextView
android:clickable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Qt1 "
android:id="#+id/protoQuantity">
</TextView>
<TextView
android:clickable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" Price1 "
android:id="#+id/protoPrice">
</TextView>
</LinearLayout>
</ScrollView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
XML of the custom pop-up: "dialog_popup.xml"
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/window"
tools:ignore="MissingConstraints">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/itemName"
android:hint="Enter the name of the item">
</EditText>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/itemQuantity"
android:hint="Enter the quantity of the item">
</EditText>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/itemPrice"
android:hint="Enter the price the item">
</EditText>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Valider"
android:id="#+id/validationButton">
</Button>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Class to create a custom pop-up: "CreateCustomPopUp.java
package com.example.myapplication;
import android.app.Activity;
import android.app.Dialog;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
public class CreateCustomPopUp extends Dialog {
private LinearLayout page;
private EditText name, quantity, price;
private Button validation;
private String varName="";
private int varQt= 0;
private float varPrice =0;
public CreateCustomPopUp(Activity activity)
{
super(activity, androidx.appcompat.R.style.Theme_AppCompat_Dialog);
setContentView(R.layout.dialog_popup);
this.page = findViewById(R.id.window);
this.name = findViewById(R.id.itemName);
this.price = findViewById(R.id.itemPrice);
this.quantity = findViewById(R.id.itemQuantity);
this.validation = findViewById(R.id.validationButton);
validation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
varName=name.getText().toString();
varQt=Integer.valueOf(quantity.getText().toString());
varPrice=Float.valueOf(price.getText().toString());
dismiss();
}
});
}
public void build()
{
show();
}
public int getQt(){
return varQt;
}
public String getName(){
return varName;
}
public float getPrice(){
return varPrice;
}
}
Main activity Java : "MainActivity.java"
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
public MainActivity activity;
public String name ="";
public int qt =0;
public float price = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.activity=this;
Button addItem = (Button) findViewById(R.id.popUpAddItem);
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CreateCustomPopUp popUp = new CreateCustomPopUp(activity);
popUp.build();
popUp.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
name = popUp.getName();
qt = popUp.getQt();
price = popUp.getPrice();
//Put/call here a function/class or whatever works that add this created item in the scrollview
}
});
}
});
LinearLayout prototypeItem = (LinearLayout) findViewById(R.id.protoItem);
prototypeItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Another popup that I'm borred to create, but I think you see the idea...
}
});
// and here is my issue : I cant reproduce this "set on click listener" for each item... because they dont already exist and I dont know how many I'll have !
}
}
Hope it's clear and you can help me ^^
bye
Use a <RecyclerView> instead. RecyclerView is the best choice when you have multiple items of same type and you have to dynamically modify them. Follow these links to learn about recycler view and click listener in recycler view RecyclerView example. Recycler View Click Listener. I will briefly discuss how to do this.
Create a item layout file. This is basically how each item of your recycler view looks. In your case this will be LinearLayout of protoitem declared in separate xml file.
Create a data model file that defines that represents your single entity. eg. Create a class Item with fields name, quantity, price and appropriate methods.
Add only recyler view in your activity_main.xml
Create an adapter that loads your data into recycler view and link your adapter to recycler view.
Create a list of your custom Item class List<Item> myList = new ArrayList<>();
Now whenever you add new Item via dialog just add your item in myList and update your adapter by adapter.notifyDataSetChanged(); Adapter will automatically add that item in your recycler view.
For click listener you need to create an interface in your adapter and implement that click listener in you main activity.
I am currently developing an android music reading app in Android Studio. The language I am using is Java but I am a beginner (sorry for my English too).
The app has several exercises. Ideally, people can click on the next or back button to see one exercise or another. The problem is that I am also looking for the user, even if he exits the application, to continue in the last exercise (image) seen.
I have read about the cycle of activities and I understand it, but since I am a beginner in the language I cannot do what I need to do. I have learned that OnSaveInstanceState or OnRestoreInstanceState do not solve my problem and that the solution may be by using SharedPreferences but I don't know how to apply it to the code I currently have. With SharedPreferences I hope I can save and restore the last imageview seen and that I can continue from there by clicking next or back.
This is the current code and it allows me to: show the initial exercise and go from one exercise to another.
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private int image_index = 0 ;
private static final int MAX_IMAGE_COUNT = 3;
private int[] mImageIds = {
R.raw.image1,
R.raw.image2,
R.raw.image3};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showImage();
}
private void showImage() {
ImageView imgView = (ImageView) findViewById(R.id.myimage);
imgView.setImageResource(mImageIds[image_index]);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case (R.id.previous_btn):
image_index--;
if (image_index == -1) {
image_index = MAX_IMAGE_COUNT - 1;
} else {
}
showImage();
break;
case (R.id.next_btn):
image_index++;
if (image_index == MAX_IMAGE_COUNT) {
image_index = 0;
} else {
}
showImage();
break;
}
}
}
This is the xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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="#android:color/background_light"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:fontFamily="#font/gilroyextrabold"
android:text="Ejercicios"
android:textColor="#android:color/black"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ImageView
android:id="#+id/myimage"
android:layout_width="wrap_content"
android:layout_height="370dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView" />
<LinearLayout
android:id="#+id/linearLayout5"
android:layout_width="match_parent"
android:layout_height="54dp"
android:layout_marginStart="10dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="40dp"
android:layout_marginEnd="10dp"
android:layout_marginRight="10dp"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#id/myimage">
<Button
android:id="#+id/previous_btn"
android:layout_width="190dip"
android:layout_height="wrap_content"
android:background="#drawable/btnatsslf"
android:onClick="onClick" />
<Button
android:id="#+id/next_btn"
android:layout_width="190dip"
android:layout_height="wrap_content"
android:background="#drawable/btnsgtslf"
android:onClick="onClick" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</LinearLayout>
</ScrollView>
As I don't have that much knowledge, I seek your help and I also receive alternatives.
put these lines after setContentView, but before showImage in onCreate
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
image_index = sp.getInt("image_index", image_index);
and save this value inside showImage just after setImageResource line
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.edit().putInt("image_index", image_index).apply();
you may keep reference to SharedPreferences sp as class member, so it won't be needed to obtain every time when showImage is called (also ImageView should be stored same way without need of findViewById everytime). also the key ("image_index") may be stored as some private static final String class member
also remember for future use: this is index in some array you have declared static. when you change it, e.g. stored value is 2 and you cut last item in images array then user get index out of bounds exception after app update installation, so inside onCreate check that this value is in range of array (just for safety)
I have a Recycler View in ItemActivity and its Adapter as a seperate class ItemAdapter.Now based on the count of the Item chosen i need to update the text on a button placed in ItemActivity.How can it be done?
note:I have passed getApplicationContext() as the context to the Adapter.It passes the GlobalValue context which I have set in the manifest.
<application
android:name=".GlobalValues"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:theme="#style/AppTheme">
The following is my ItemActivity.xaml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
tools:context=".ItemPickerActivity">
<TextView
android:id="#+id/itemstext"
android:layout_marginTop="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Choose Items"
android:fontFamily="#font/exo_semibold"
android:textColor="#color/dark_grey"
/>
<android.support.v7.widget.RecyclerView
android:layout_marginHorizontal="3dp"
android:id="#+id/pickerRecview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/itemstext"
android:layout_marginTop="7dp" />
<RelativeLayout
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="50dp"
android:padding="10dp"
android:id="#+id/checkout"
android:clickable="true"
android:background="#color/go_green"
>
<TextView
android:id="#+id/Total"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rs XXX"
android:layout_marginLeft="5dp"
android:textSize="18sp"
android:textColor="#color/white"
android:layout_centerVertical="true"
android:fontFamily="#font/exo_semibold"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Checkout"
android:textColor="#color/white"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:textSize="22sp"
android:fontFamily="#font/exo_semibold"
/>
<TextView
android:id="#+id/TotalItems"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:text="xx Items"
android:fontFamily="#font/exo_semibold"
android:textColor="#color/white"
android:textSize="18sp" />
</RelativeLayout>
</RelativeLayout>
And this is how i instantiate the adapter object
ItemPickerAdapter adapter = new ItemPickerAdapter(getApplicationContext(), ItemsList);
recyclerView.setAdapter(adapter);
I need to change the value of ItemCount in my ItemActitvity from the adapter!Please advise me on how it is possible.Thanks!
The easiest way would be to make the Adapter class an inner class contained within the Activity class. Then make the View you need to manipulate a global variable.
You can do the following
Create one interface
public interface ItemCountListner {
void onItemCountUpdate(int count);
}
Implement interface in your activity and pass the reference to your adapter
class MainActivity implements ItemCountListner {
---------
ItemPickerAdapter adapter = new ItemPickerAdapter(MainActivity.this, ItemsList, this);
---------
//implemented method
void onItemCountUpdate(int count){
// update your ui
}
}
Add argument in your adapter constructor
public ItemPickerAdapter(Context context, List itemList,
ItemCountListner listener)
Update your ui by calling
listener.onItemCountUpdate(count);
Inside your RecyclerView Adapter, you can define your own viewModel and inside that, you can attach onClick on any component you want. For eg:
public class MyViewHolder extends RecyclerView.ViewHolder
{
private TextView eachFeaturesName;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
eachFeaturesName = itemView.findViewById(R.id.eachFeaturesName);
}
}
And inside onBindViewHolder function , you can do this:
public void onBindViewHolder(#NonNull final MyViewHolder myViewHolder, final int position) {
//myViewHolder.eachFeaturesName.setonViewClickListener(...)
}
This is an easy way to use onClickListener on RecyclerView
Change the adapter instantiation in your activity from:
ItemPickerAdapter adapter = new ItemPickerAdapter(getApplicationContext(), ItemsList);
to this:
ItemPickerAdapter adapter = new ItemPickerAdapter(this, ItemsList);
meaning you pass the activity's context and not the application's context.
Then in your adapter class declare this:
MainActivity mainActivity = (MainActivity) context;
replace MainActivity with your activity's class name and context with the name of the parameter of your adapter class constructor for the Context.
Now you can access every public method, property, view in your activity by:
mainActivity.something
Edit1: Use a variable in your activity class
Context mainContext = this;
then instantiate the adapter:
ItemPickerAdapter adapter = new ItemPickerAdapter(mainContext, ItemsList);
Edit2: If you want to access your activity's UI elements like a TextView from your adapter, create a public method inside the activity class:
public void setTextViewText(String text) {
myTextView.setText(text);
}
and call it from the adapter:
mainActivity.setTextViewText("some text");
I am new. Whenever i try to build and run this code this message appears.
Here is the XML code:
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:orientation="vertical"
tools:context="com.example.android.justjava.MainActivity">
<TextView
android:id="#+id/quantity_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="quantity"
android:textAllCaps="true"
android:textSize="16sp"
android:textColor="#android:color/black"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"/>
<TextView
android:id="#+id/zero_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:layout_below="#+id/quantity_text_view"
android:textSize="16sp"
android:textColor="#android:color/black"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="order"
android:textAllCaps="true"
android:layout_below="#+id/zero_text_view"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:onClick="submitOrder"/>
Here is the Java code:
/** * IMPORTANT: Add your package below. Package name can be found in
the project's AndroidManifest.xml file. * This is the package name
our example uses: * * package com.example.android.justjava; * */
import android.R; import android.os.Bundle; import
android.support.v7.app.AppCompatActivity; import android.view.View;
import android.widget.TextView;
import static com.example.android.justjava.R.id.quantity_text_view;
/** * This app displays an order form to order coffee. */ public
class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}
/**
* This method is called when the order button is clicked.
*/
public void submitOrder(View view) {
display(1);
}
/**
* This method displays the given quantity value on the screen.
*/
private void display(int number) {
TextView quantityTextView = (TextView) findViewById(R.id/quantity_text_view);
quantityTextView.setText("" + number);
} }
Here is the pic of the error:
https://i.stack.imgur.com/tlrUi.png
Please Help me
Check your xml file name.
Check your imports statement
Clean and build the project again.
if above does not work then Delete the R file and clean it
check package name is matching here
tools:context="com.example.android.justjava.MainActivity"
other isssue is "\" in your findValueById in place of "."
provide the file name of the layout exactly.. I think your layout file name is activity_main and not main_activity.
Your display function like below.
private void display(int number) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + number);
} }
Threre is "\" in your findValueById in place of "."
Remove this line tools:context="com.example.android.justjava.MainActivity"
this line is for activity name but i think you copy paste XML of MainActivity.java
and that layout is not of MainActivity. you should remove this line it does not create any error.
On the right side of your screen app-->res-->Layout, check what is the name of the activity it may be activity_main_java.xml so you have to replace the R.layout.main_activity by R.layout.activity_main_java
Check import of Resource(R). that is pointing other module or library.
I feel like either I'm missing a vital point in OOP, or my constructor is wrong. I keep getting a null pointer exception when creating my object.
The logcat is saying that its coming from the first line of the '// default constructor'.
Here is the code for my class:
package com.chriswahlfeldt.homeworkapp;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
public class MyHomework extends Activity {
private EditText title, description;
private View homeworkView, activityView;
// default constructor
public MyHomework() {
homeworkView = getLayoutInflater().inflate(R.layout.add_homework, null);
activityView = getLayoutInflater().inflate(R.layout.activity_my, null);
title = (EditText) homeworkView.findViewById(R.id.classTitleET);
title.setText("");
description = (EditText) homeworkView.findViewById(R.id.descriptionET);
title.setText("");
}
public View getContentView_activity_my() { return activityView; }
public View getContentView_add_homework() { return homeworkView; }
public String getTitleTxt() { return title.getText().toString(); }
public String getDescriptionTxt() { return description.getText().toString(); }
public void setTitleTxt(String thatString) { title.setText(thatString); }
public void setDescriptionTxt(String thatString) { title.setText(thatString); }
}
And here is where it is used:
package com.chriswahlfeldt.homeworkapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MyActivity extends Activity
{
private MyHomework hW = new MyHomework();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(hW.getContentView_activity_my());
final Button addHWBtn = (Button) findViewById(R.id.HWBtn);
addHWBtn.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(hW.getContentView_add_homework());
}
});
}
}
.xml file: activity_my.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MyActivity"
android:id="#+id/mainRelLayout" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/HWBtn"
android:textSize="25sp"
android:paddingLeft="50dp"
android:paddingRight="50dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:hint="+Homework"/>
</RelativeLayout>
.xml file: add_homework.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:alpha=".8">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/classTitleET"
android:layout_gravity="top"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:capitalize="sentences"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="10dp"
android:hint="Class Title"
android:textSize="20sp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="8"
android:id="#+id/descriptionET"
android:layout_below="#+id/classTitleET"
android:layout_alignLeft="#+id/classTitleET"
android:layout_alignStart="#+id/classTitleET"
android:layout_alignRight="#+id/classTitleET"
android:layout_alignEnd="#+id/classTitleET"
android:hint="Homework Description"
android:textSize="20sp"
android:height="120dp"
android:gravity="top" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/createBtn"
android:hint="Create"
android:textSize="20sp"
android:layout_below="#+id/descriptionET"
android:layout_alignLeft="#+id/descriptionET"
android:layout_alignStart="#+id/descriptionET"
android:layout_alignRight="#+id/descriptionET"
android:layout_alignEnd="#+id/descriptionET" />
</RelativeLayout>
Thx!
yout can't call getLayoutInflater() directly , you need to call it on an instance of the LayoutInflater class.
try this
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
homeworkView = inflater.inflate(R.layout.add_homework, null);
you can replace context with "this" if you are calling this inan activity
It's a bad practice to put the code inside a constructor for activities. You can put in the OnCreate method.
If you need this instance really.
You can do the following
public class MyHomework extends Activity {
private EditText title, description;
private View homeworkView, activityView;
private static MyHomework instance;
#Override
protected void onCreate(Bundle savedInstanceState) {
instance = this;
}
public static MyHomework getActivity() {
return instance;
}
}
public class MyActivity extends Activity
{
private MyHomework hW = MyHomework.getActivity();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.....
}
}
You cannot call activity methods or use the activity as a Context before onCreate() in the activity lifecycle. Instance initialization including constructor is too early. As a consequence, you rarely need to use an explicit constructor with activities.
Never instantiate activity classes with new. Related to the point above: such objects are not really good for anything since they are not properly initialized as activities and their activity lifecycle methods such as onCreate() are not invoked.
It looks like your MyHomework should not be an activity at all:
Remove the `extends Activity``
Pass in a Context as an argument to methods that need it. For example,
public MyHomework(Context context) {
homeworkView = LayoutInflater.from(context).inflate(...)
Invocation from MyActivity onCreate() (not member variable init, too early):
homework = new MyHomework(this)