accessing intent views from activity class to java class - android

I have one java class and one Activity class.
In my java class, it consists of business logic. I want to access the Textviews from activity class to my java class.
If I create an object to activity class. I got all views in activity class as NULL and getting null pointer Exception.
This is my java class here I have created object for activity class and here I am getting NULLpointerException for tdoor.setText() method.
public class Subscribe {
viewtiles vtiles=new viewtiles();
public void sendMessageforstatus(String status)
{
if(status.contains("Door is open"))
{
vtiles.tdoor.setText("OPEN");
}
else if(status.equalsIgnoreCase("Door is close"))
{
vtiles.tdoor.setText("CLOSE");
}
This is my activity layout class
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tilesview);
tdoor = (TextView) findViewById(R.id.door2);
}
XML
<RelativeLayout xmlns:android="schemas.android.com/apk/res/android";
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/background_light" >
<TextView android:layout_width="79dp"
android:layout_height="wrap_content"
android:text="Door"
android:layout_marginTop="10dp"
android:layout_marginLeft="52dp"
android:id="#+id/door1"
android:textColor="#android:color/black"
android:textSize="20dp" />
</RelativeLayout>
Can u plzzz help me for this problem...

You can pass TextView object into your Java class,
public void sendMessageforstatus(String status, TextView txt)
{
// example
txt.setText("OPEN");
}

Related

Hide/Show Button in Fragment from Activity

i am trying to hide/show Button in fragment from Activity but it give me following exception.
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Home Activity
public class HomeActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
CategoryFragment frag=(CategoryFragment) activity.getSupportFragmentManager()
.findFragmentByTag("cat_frag");
Button newDesigns= (Button) frag.getView().findViewById(R.id.new_designs);
newDesigns.setVisibility(View.VISIBLE);
}
}
Category Fragment
public class CategoryFragment extends Fragment{
Button newDesigns;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_category, null);
newDesigns= (Button) v.findViewById(R.id.new_designs);
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#CCCCCC">
<TextView
android:id="#+id/list_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#drawable/shape_logo_bg"
android:gravity="center"
android:padding="5dp"
android:textColor="#android:color/white"
android:textSize="18sp" />
<Button
android:id="#+id/new_designs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/list_name"
android:background="#color/edit_button_color"
android:padding="10dp"
android:text="#string/new_designs"
android:textColor="#color/btn_text_color"
android:layout_centerHorizontal="true"
android:layout_marginTop="5dp"
android:visibility="gone"
/>
</RelativeLayout>
Code is too large to be posted here. Thats why i have only posted the code where i am finding an issue.
I am able to get newDesigns BUTTON instance.What is shocking for me is if try to play with button instance (VISIBLE/GONE) it gives me above mentioned exception.
Help is appreciated.
You shouldn't play with a view of the Fragment while you are in a Activity directly. You will not know what the view's state will be and this can potentially lead to issues you can't even think of(beleive me i faced many). To interact with the activity's views, make an interface:
public interface AccessFragmentViews{
public void setVisibilityForButton(boolean bool);
//any other methods that you need
}
Now implement this inside the fragment class and override the method.
class YourFragment implements AccessFragmentViews{
.
.
public void serVisibilityForButton(boolean shouldHide){
if(shouldHide){
yourButton.setVisibility(View.GONE);
}else{
yourButton.setVisibility(View.VISIBLE);
}
}
}
Now you can interact safely with the views of the fragment within a activity using this interface. Make sure that the fragment is alive before doing so though ;) accessing child's view are prone to WindowLeakedExceptions and illegalstateexceptions
In the activity use it as follows:
you can get the fragment reference by either finding it by its tag or by using the reference you used to create the fragment
//NOTE: it is very very dangerous to do the accessing on a fragment views from an activity
//first the alive check then the logic
if(yourFragmentReference!=null){
((AccessFragmentViews)yourFragmentReference).setVisibilityForButton(true);// or false if you want to make it visible
}
Add a method in your fragment class
public void changeButtonVisibility(boolean visibility){
if(visibility){
newDesigns.setVisibility(View.VISIBLE);
}else{
newDesigns.setVisibilty(View.GONE);
}
}
and in your activity class
add this line
public class HomeActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
CategoryFragment frag=(CategoryFragment) activity.getSupportFragmentManager()
.findFragmentByTag("cat_frag");
frag.changeButtonVisibility(true);
}
}

why the app crash after calling a method?

I hope you can help me I was trying to look into the other questions but I didnt found what I was trying to do or didn't get it.
this is a very simple example of what I'm trying to do. I have this main activity:
public class MainActivity extends Activity {
static EditText num1, num2; //Change EditText from TextView
static TextView num3; //Textview variable
int x, y, r;
Addition addition=new Addition();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num1=(EditText)findViewById(R.id.editText);
num2=(EditText)findViewById(R.id.editText2);
num3=(TextView)findViewById(R.id.textView);
x = 0;
y = 0;
}
public void add (View view){
setXY();
r=addition.addResult(x,y);
num3.setText(String.valueOf(r));
}
public void setXY(){
x=Integer.parseInt(num1.getText().toString());
y=Integer.parseInt(num2.getText().toString());
}
}
and I am trying to call that method from this class
public class Addition {
public int addResult(int x, int y){
return x+y;
}
}
so at the beginning the app crashed because of the null values that was receiving from the layout, but after set the try catch the app was running. The problem comes when I click the "add" button the app crash again. do you guys can tell me why? what am I doing wrong? how should I do it? and if I have an app with more "operations" ,methods, is it worth creating a class with all this operations and call them from the main one? or maybe I shouldn't try to do this?
Greetings!!!
Chiok
Logcat
07-14 14:35:24.625 5407-5407/com.chiok.x2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.chiok.x2, PID: 5407
java.lang.IllegalStateException: Could not find method addition(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.widget.Button with id 'button'
at android.view.View$DeclaredOnClickListener.resolveMethod(View.java:4479)
at android.view.View$DeclaredOnClickListener.onClick(View.java:4443)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
07-14 14:35:25.893 5407-5407/com.chiok.x2 I/Process: Sending signal. PID: 5407 SIG: 9
and this is the xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
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.chiok.x2.MainActivity">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText2"
android:layout_below="#+id/editText"
android:layout_centerHorizontal="true"
android:layout_marginTop="52dp"
android:onClick="add" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_below="#+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="71dp"
android:onClick="addition" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/textView"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="56dp" />
I guess it have something to do with the editable objets that are null.. but nothing that I try works.
change these code
num1=(TextView)findViewById(id.editText);
num2=(TextView)findViewById(id.editText2);
num3=(TextView)findViewById(id.editText3);
to
num1=(TextView)findViewById(R.id.editText);
num2=(TextView)findViewById(R.id.editText2);
num3=(TextView)findViewById(R.id.editText3);
and remember to import R.java in your project.
onClick command which stored in layout need parameter View v in receiver method, so change addResult() to addResult(View v)
if I have an app with more "operations" ,methods, is it worth creating
a class with all this operations and call them from the main one?
Yes it worths that, it will make your code more object oriented. In this case it will make more sense if you change the name of class from Addition to Operations. Also Addition class does not need to be an activity. So don't extend it from MainActivity.
Just send two parameter to that method and make addResult return an int result which is addition of those two parameters.
And in your MainActivity get the return value of your addResult method and setText the edittext3.
public class MainActivity extends Activity {
TextView num1, num2,num3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num1=(TextView)findViewById(R.id.editText);
num2=(TextView)findViewById(R.id.editText2);
num3=(TextView)findViewById(R.id.editText3);
// here I am trying to call the method
Addition x = new Addition();
int param1 = Integer.parseInt(num1.getText().toString());
int param2 = Integer.parseInt(num2.getText().toString());
int result = x.addResult(param1, param2);
num3.setText(String.valueOf(result));
}
}
And your Addition Class can be like this;
public class Addition {
public int addResult(int param1, int param2){
return param1 + param2;
}
}
Summary I changed setContentView(R.layout.activity_main);
Delete extends MainActivity in your Addition class.
Also if the error still persists, I need to see your xml layout where you define your textviews and button.
Make your Textview static. Try
static TextView num1, num2,num3;
Reason
Addition x = new Addition();
In the above code, it is creating a new instance of Addition class which is extending the MainActivity and hence the TextView will be NULL for the new instance. In order to make the TextView initialization available for all instances, make the TextView static.
Use following code.
public class MainActivity extends Activity {
EditText num1, num2; //Change EditText from TextView
TextView num3; //Textview variable
Button add; //Button variable
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //Add R.layout.activity_main
num1=(EditText)findViewById(R.id.editText); //R.id.editText
num2=(EditText)findViewById(R.id.editText2); //R.id.editText2
num3=(TextView)findViewById(R.id.textview); // initialize textview
add=(Button) findViewById(R.id.add); //initialize add button
final Addition x = new Addition();
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
x.addResult();
}
});
}
}
public class Addition {
public void addResult(){
try {
num3.setText(String.valueOf((Integer.parseInt(num1.getText().toString())+(Integer.parseInt(num2.getText().toString())))));
}
catch (Exception e) {}
}
}
}

error on setOnclickListener in my activity

((Button)findViewById(2131230768)).setOnClickListener(new MainMenuActivity(this));
View.OnClickListener runGameListener = new MainMenuActivity(this);
I have implemented onclicklistener even though it gives error on mainmenuactivity
my class is
public class MainMenuActivity
extends Activity implements OnClickListener
please help me..
Assume you have layout sample_activity.
Here's the code for sample_activity.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GO!!"
android:id="#+id/buttonGo"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="170dp" />
</RelativeLayout>
And MainActivity.class :
public class MainActivity extends ActionBarActivity {
Button goButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sample_activity);
goButton = (Button) findViewById(R.id.buttonGo);
goButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//....Do all the stuffs here
}
});
}
First, never search for views by their generated id value. Use the identifier name instead, e.g.
findViewById(R.id.your_button)
Second, new with an Activity is not correct. Don't instantiate activities yourself.
Since your activity implements View.OnClickListener and assuming the code is in the same activity, just use
setOnClickListener(this)
That is,
findViewById(R.id.your_button).setOnClickListener(this);
(setOnClickListener() is a View method so casting to Button is not needed here.)
Firstly check your id of button from xml is write or not? I think your id is wrong its giving error..

Not able to set source of an imageview in Included layout in an activity

I have created two XML layout and Activity respecively.
A XML file A contains a layout with Image view Pointed to Activity A.
A XML file B, in that i included XML A and made Activity B extends Acitivity A
In Acivity A oncreate i set the image source for the XML file A. but its not setting the image source and not getting any error also. Plz help me
Here is my code
Xml A
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/MasterBaseLayOut"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<ImageButton
android:id="#+id/imagebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true" />
</RelativeLayout>
XML B
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<include
android:id="#+id/Master"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
layout="#layout/xmlA" />
<Button
android:id="#+id/btn1"
android:onClick="btn1_onclick"
android:text="#string/title_1"/>
</RelativeLayout>
Activity A
public class ActivityA extends Activity{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.XMLA);
ImageButton img1 =(ImageButton)findViewById(R.id.imagebutton);
img1.setBackgroundResource(R.drawable.imgtest);
}
}
Activity B
public class ActivityB extends ActivityA {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.XmlB);
}
}
Tough you have no code, but i assume you are not getting the imageView in Activity B.So in Activity
B's onCreate() method call the Activity A's onCreate using super keyword,most probably you will get the imageview with source image.
public void onCreate(Bundle b) {
super.onCreate(b);
}
This is what you have:
ActivityA extends ActivityB
This is what it should be:
ActivityB extends ActivityA
Also, you should consider pressing "Ctrl + Shift + F" to format your code, just a little tip.

Java program does not execute in Android

I am doing a weather project in android. The information is from a given URL which is static and contains a list of cities. For example: HTTP://myexample/info/?cities displays a list of cities. HTTP://myexample/info/?tokyo will display: Tokyo, Japan.
I have done the layout to write down the name of the city to be executed:
xmlns:tools=["http://schemas.android.com/tools"]
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Meteo" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="40dp"
android:weightSum="4">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="3">
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/soleil" />
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="4">
<EditText
android:id="#+id/editText1"
android:layout_width="170dp"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button" />
</LinearLayout>
But the Java program doesn't execute. Only the layout is executed:
public class Demo {
public static void main(String[] args) {
// URL
String url = "$HTTP://myexample/info/?cities$";
// Weather information
String weather = "Tokyo, Japan#15.5#Sun ##";
// Get the city name
String city = url.substring(url.indexOf("?") + 1).trim();
System.out.println(city);
// Check the weather of the city: 15.5#Sun
// Remove city name
// Remove last #
if (weather.toLowerCase().contains(city.toLowerCase())) {
// Get condition:
String condition = weather.substring(weather.indexOf("#") + 1,
weather.length() - 2);
System.out.println(condition);
// Split with # sign and you have a list of conditions
String[] information = condition.split("#");
for (int i = 0; i < information.length; i++) {
System.out.println(information[i]);
}
}
}
}
Where is the problem?
Look up Activities. In Android you'll have to create a class that extends Activity. The equivalent to the main() method is the OnCreate() method. In this method you can set your layout with setContentView(layout id)
Ofcourse main() method is not supported in android.
public static void main(String[] args) {
// ....
}
Use Activity instead.
public class MyActivity extendsActivity
{
#Override
protected void onCreate(Bundle saveInstance)
{
// This method will be called first
super.onCreate(saveInstance);
// Your definition
}
}
Your main problems is that you are trying to run an Android application as a Java application.
public static void main(String[] args)
Is the standard entry point for a Java application.
In Android, things are a little different.
First, class Demo must extend Activity:
public class Demo extends Activity
Second, you have to implement special methods, which are invoked at specific moments of the life time of your application, the most important being:
public void onCreate(Bundle savedInstanceState) { }
protected void onPause() { }
protected void onResume() { }
You should check the corresponding documentation at Android Developers Site.

Categories

Resources