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.
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)
My EditText does not work like the videos and articles I have found. The EditText does not show what the user inputted at the time of input or when I tell the output to show there, the hint I assigned it also does not show up. Right now I have the output going to a TextView but can greatly reduce lines of code if I can get the EditText working properly. I am new to this and have troubles understanding. Thank you for the help.
Here is the xml file:
//DOES NOT SHOW INPUT AT TIME OF INPUT, OR WHEN TOLD TOLD BY OUTPUT. HINT DOES NOT SHOW EITHER-------
<EditText
android:id="#+id/MetalCounter"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_margin="4dp"
android:ems="10"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="15sp"
android:hint="0"
android:textColorHint="#000000"
android:inputType="number"
app:layout_constraintRight_toLeftOf="#id/guideline"
app:layout_constraintTop_toBottomOf="#id/ResourceSubmitButton" />
//is put in top left corner for testing purposes---------------------------------
<TextView
android:id="#+id/MetalResult"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_margin="4dp"
android:text=""
android:textAlignment="center"
android:textColor="#000000"
android:textSize="15sp"
/>
and here is the java file:
package com.example.game;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
// These are the global variables
EditText MetalCounter;
TextView MetalResult;
Button ResourceSubmitButton;
int Metal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//to get from user input and into variable form
MetalCounter = (EditText) findViewById(R.id.MetalCounter);
MetalResult = (TextView) findViewById(R.id.MetalResult);
ResourceSubmitButton = (Button) findViewById(R.id.ResourceSubmitButton);
//Submit button
ResourceSubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//to receive and show the inputted values into the MetalResult TextView
MetalResult.setText(MetalCounter.getText().toString());
//This is a test to see if the result would show up but does not
Metal = Integer.parseInt(MetalCounter.getText().toString());
MetalCounter.setText(MetalCounter.getText().toString());
}
});
}
}
Well, I think the problem lies here in this part
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_margin="4dp"
android:ems="10"
android:textSize="15sp"
These attributes are not well-defined because you have set the layout_margin to 4dp which causes the view to shrink. so instead of having a width of 40dp, now you have a width of 32dps, similarly you have a height of only 12dps which is very small and doesn't match with the selected textSize
So, my suggestion is changing the width and height attributes to wrap_content as follows
android:layout_width="wrap_content"
android:layout_height="wrap_content"
and you can keep everything else as it's.
Remarks
Consider changing your variables to follow the camelCase convention
// Before
EditText MetalCounter;
TextView MetalResult;
//After
EditText metalCounter;
TextView metalResult;
Change the hint color's opacity in order to differentiate it from the text itself
If you still have a problem so it may be due to the constraints in the bottom. If so, please post the full layout file.
I am quite new to Android, and this is the first project I've decided to work on. Although I have declared my buttons (addButton, subtractButton, etc.) within the MainActivity.java file and have assigned them to their respective buttons within the XML file, I'm still receiving an error when I run my app. I believe this is because, within the OnClick method, the IDs for the view elements within the XML file are being recognized. For example, the ID of my '+' button is add_button in the XML, but when I try to write
case R.id.addButton, I receive an error (but case R.id.add_button doesn't return an error).
import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity implements View.OnClickListener {
Button addButton;
Button subtractButton;
Button multiplyButton;
Button divideButton;
TextView editText;
EditText number1;
EditText number2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addButton=(Button)findViewById(R.id.add_button);
multiplyButton=(Button)findViewById(R.id.multiply_button);
subtractButton=(Button)findViewById(R.id.subtract_button);
divideButton=(Button)findViewById(R.id.divide_button);
editText=(TextView)findViewById(R.id.dispNum);
number1=(EditText)findViewById(R.id.num1);
number2=(EditText)findViewById(R.id.num2);
addButton.setOnClickListener(this);
multiplyButton.setOnClickListener(this);
subtractButton.setOnClickListener(this);
divideButton.setOnClickListener(this);
}
public void onClick(View v){
int num1=0,num2=0,result=0;
num1=Integer.parseInt(number1.getText().toString());
num2=Integer.parseInt(number2.getText().toString());
switch(v.getId()){
case R.id.addButton:
result=num1+num2;
break;
case R.id.subtract_button:
result=num1-num2;
break;
case R.id.multiply_button:
result=num1*num2;
break;
case R.id.divide_button:
result=num1/num2;
break;
default:
break;
}
editText.setText(result);
}
}
This is the XML file
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/num1"
android:gravity="center"
android:id="#+id/num1"/>
<EditText
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="#string/num2"
android:gravity="center"
android:id="#+id/num2"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="20dp">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="+"
android:id="#+id/add_button"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="-"
android:id="#+id/subtract_button"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="*"
android:id="#+id/multiply_button"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="/"
android:id="#+id/divide_button"/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="30dp"
android:gravity="center"
android:textSize="24dp"
android:id="#+id/dispNum"/>
Thanks for any help in advance!
I think the problem is wrong ids you are getting into a switch case
look closely , in your xml the id of add button is "add_button" where as the case you are using for it is
case R.id.addButton:
so this is not the right and actual id of the add button . Please check twice further that you did not have messed up with ids.
in onClick you need to provide ids add_buttonyou define in xml not that button variable you define in MainActivity which is Addbutton
this is not any issue this is how android onClick works.
Check your onclick method you have used wrong id in switch case.
use R.id.add_button instead of R.id.addButton
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 !