Accessed from within inner Class - android

I am very new to Android programming and have a little problem.
The Error is:
Variable 'Demo_Button' is accessed from within inner class. Needs to declared final.
What i tried:
changed Demo_button.setImageResource(R.drawable.pressed); to final Demo_button.setImageResource(R.drawable.pressed);
package com.iklikla.eightgame;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.ImageButton;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ImageButton Demo_button = (ImageButton)findViewById(R.id.imageButton);
Demo_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Demo_button.setImageResource(R.drawable.pressed);
}
});
}
}

A couple options here
First, I would declare it as a member variable then it will work
public class MainActivity extends Activity {
ImageButton Demo_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Demo_button = (ImageButton)findViewById(R.id.imageButton);
Second, since you are changing the View being clicked you can access it that way
emo_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ImageButton btn = (ImageButton)v; // cast the View to an ImageButton
btn.setImageResource(R.drawable.pressed);
}
});
Not related but will give you an error at runtime with the current code, you need to inflate a layout before trying to initialize that Button (most likely with setContentView()). So using my first example it would look something like
public class MainActivity extends Activity {
ImageButton Demo_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_layout); // where my_layout is the name of your layout
// file containing the Button without the xml extension
Demo_button = (ImageButton)findViewById(R.id.imageButton);

Related

android hiding ui and showing ui code not working [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 6 years ago.
package com.example.eiraj.listviewseefrgmentsfiirst;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView= (TextView) findViewById(R.id.textView);
public void show(View view){
textView.setVisibility(View.VISIBLE);
}
public void hide(View view){
textView.setVisibility(View.INVISIBLE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
here two buttons are being used to show data and hide data but whenever I try to run it emulator shows the message unfortunately uihide stopped also I downloaded the apk to run it on my phone but same message came there
Move TextView textView= (TextView) findViewById(R.id.textView); inside onCreate
while keeping textView reference outside onCreate because before the execution of onCreate there is no layout attached to your activity , hence the issue
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView= (TextView) findViewById(R.id.textView);
}
Then your MainActivity.java will be
public class MainActivity extends AppCompatActivity {
TextView textView;
public void show(View view){
textView.setVisibility(View.VISIBLE);
}
public void hide(View view){
textView.setVisibility(View.INVISIBLE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView= (TextView) findViewById(R.id.textView);
}
}
Plus you can also use textView.setVisibility(View.GONE); if you want to completely make your view invisible
Attach your TextView inside onCreate():
package com.example.eiraj.listviewseefrgmentsfiirst;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView= (TextView) findViewById(R.id.textView);
}
public void show(View view){
textView.setVisibility(View.VISIBLE);
}
public void hide(View view){
textView.setVisibility(View.INVISIBLE);
}
}
We can't initialize Views before setContentView() is called and it is compulsory to call setContentView() inside onCreate() method.
Do like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView= (TextView) findViewById(R.id.textView);
}

Android generate new objects from onClick

I try to develop a simple Android App with one Button which generates new TextViews on each click.
import android.app.Activity;
import android.os.Bundle;
import android.text.Layout;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class CreateTV extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button mCreate = (Button)findViewById(R.id.btnCreate);
mCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
((Button) v).setText("Clicked");
TextView mTV1 = new TextView(this);
}
});
}
}
My code is wrong because of:
TextView mTV1 = new TextView(this);
I could find some similar examples, which generate objects programmatically in onCreate(). But I want to generate and modify new objects in onClick().
Would anybody please help?
Change
TextView mTV1 = new TextView(this);
to
TextView mTV1 = new TextView(CreateTV.this);
Views can only be instantiated with a context as parameter
As you can see in the documentation a TextView needs the context to be created. TextView(Context context)
Since you are trying to create a TextView inside a ClickListener you can not use this as a reference to a Context-extending object.
As McAdam331 pointed out, use new TextView(getActivity), this works because Activity extends Context.
In addition to change TextView mTV1 = new TextView(this); to TextView mTV1 = new TextView(CreateTV.this);, you must add the TextView within a view like the following:
import android.app.Activity;
import android.os.Bundle;
import android.text.Layout;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class CreateTV extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button mCreate = (Button)findViewById(R.id.btnCreate);
mCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
((Button) v).setText("Clicked");
TextView mTV1 = new TextView(CreateTV.this);
addContentView(mTV1);
}
});
}
}
I would prefer adding a Context, setting it to final and then call the Textview using the Context.
Example:
public class CreateTV extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button mCreate = (Button)findViewById(R.id.btnCreate);
final Context mContext = this;
mCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
((Button) v).setText("Clicked");
TextView mTV1 = new TextView(mContext);
addContentView(mTV1);
}
});
}
}
If you want to use the Context outside the onCreate method (and within Listeners) you can define a Context.
private Context context;
public void onCreate(....) {
this.context = this;
}
private void aMethod() {
context....
}
Theres another way doing such cool stuff. Create a Class and extends it by Application.
public class MainApplication extends Application {
public static Context getContext() { return this; }
}
Then add the MainApplication to your Manifest.
<application
android:name=".MainApplication"
>
and access it from everywhere with MainApplication.getContext();

Android TextView and Buttons not working in my app

I am learning Android and trying one simple Android app development, I got one demo code from my lecture and the teacher simply do the following:
There are 2 buttons, 1 textview. When touching button A, it will show "text A" in the textview, while touching button B, it will present "text B" in textview.
I followed the code and rewrote it, but i can't get the correct result when I ran with emulator.
When I touch either button, there's no content in the TextView. But my teacher's reference code works:
import android.view.View;
import android.widget.TextView;
import android.os.Bundle;
import android.app.Activity;
public class ActTwo extends Activity {
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_act_two);
tv = (TextView) this.findViewById(R.id.textView2);
}
public void report(View v) {
if(v.getId() == R.id.button1)
tv.setText(R.string.anrep);
else
tv.setText(R.string.iprep);
}
}
How is report(View v) called? I can't understand how this class is called. Could someone please help me out?
You need to let your button know that, when pressed, report() should be called. This may be done through the android:onClick attribute of your button on your layout's XML:
<Button
android:id="#+id/button1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/button_text"
android:onClick="report" />
Or by code, attaching an OnClickListener to the button:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_act_two);
button1 = (Button) this.findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
report(v);
}
});
}
Hope it helps.
You should implements the View.OnClickListener, and override that OnClick method. You also need to setOnClickListener on your buttons. So your code should be like:
import android.view.View;
import android.widget.TextView;
import android.os.Bundle;
import android.app.Activity;
public class ActTwo extends Activity implements View.OnClickListener{
private TextView tv;
private Button button1, button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_act_two);
tv = (TextView) this.findViewById(R.id.textView2);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.button1)
tv.setText(R.string.anrep);
else
tv.setText(R.string.iprep);
}
}
import android.view.View;
import android.widget.TextView;
import android.os.Bundle;
import android.app.Activity;
public class ActTwo extends Activity {
private TextView tv;
private Button button1, button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_act_two);
tv = (TextView) this.findViewById(R.id.textView2);
button1 =(Button)this.findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v){
report(v);
}
});
button2 =(Button)this.findViewById(R.id.button2):
button2.setOnClickListener(new OnClickListener(){
public void onClick(View v){
report(v);
}
});
}
public void report(View v) {
if(v.getId() == R.id.button1)
tv.setText(R.string.anrep);
else
tv.setText(R.string.iprep);
}
}

ListView: Null pointer exception

Good day. I'm having some issues with my android project specifically listview. I tried searching for other information here in this site, and implemented some of the answers. However, it is still not working.
The error specifically is
NullPointerException at line 76 at MainActivity
Here is the code of my MainActivity
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity {
final ArrayList<String> studentName = new ArrayList<String>();
ArrayAdapter<String> aa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView myList = (ListView) findViewById(R.id.listName);
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, studentName);
myList.setAdapter(aa);
//droid.R.id.list;
//add
Button bAdd = (Button) findViewById(R.id.addstudent);
bAdd.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
startActivity(new Intent("android.intent.action.ADDSTUDENTS"));
}
});
//edit
Button bEdit = (Button) findViewById(R.id.editstudent);
bEdit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View x) {
startActivity(new Intent("android.intent.action.EDITSTUDENTS"));
}
});
//edit
Button bDelete = (Button) findViewById(R.id.deletestudent);
bDelete.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View x) {
startActivity(new Intent("android.intent.action.DELETESTUDENTS"));
}
});
}
public ArrayList<String> getArray(){
return studentName;
}
public void notifyArray(){
aa.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
and line 76 by the way is
aa.notifyDataSetChanged();
Here is my code for the AddStudents class
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AddStudents extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_student);
Button bAddStudents = (Button) findViewById(R.id.add);
final EditText et = (EditText) findViewById(R.id.student_name);
bAddStudents.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
MainActivity as = new MainActivity();
as.getArray().add(et.getText().toString());
as.notifyArray();
finish();
}
});
Button bBack = (Button) findViewById(R.id.backadd);
bBack.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
finish();
}
});
}
}
and the xml part with the list view is
<ListView
android:id="#+id/listName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ListView>
I hope you can help me cause I want to also learn what my mistakes are. I can add other information if you want.
In your AddStudents class, you're calling notifyArray() right after you instantiated MainActivity. MainActivity.onCreate() will not be called just by instantiating it.
Instantiating your MainActivity there is probably not what you want anyway (because that object will be disposed directly after the onClick handler is done).
What you want instead is to access the existing instance of MainActivity. For that, add a reference to the current instance to a static member of your MainActivity class, e.g.
public class MainActivity extends Activity {
public static MainActivity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
activity = this;
}
}
Then in your AddStudent class access it via
MainActivity.activity.notifyArray()
This is not the most beautiful way to solve your issue, but it works as long as you can be sure to only have one MainActivity instance. (If not, you could make the array itself static; or create a Singleton wrapper class for it.)
notifyArray() is being called before onCreate.
Try calling getArray().add(et.getText().toString()); and notifyArray(); inside onResume() of MainActivity and NOT from AddStudentActivity( not recommended!)
So onResume() you would ideally want to add a new student to the list, so in your case, you can retrieve the student name using a common sharable object like a hashtable or somethiing similar, make it a singleton, and use it from anywhere in the applciation
The common class may go something like:
class CommonHashtable{
private static Hashtable<String, Object> commonHashtable = null;
public static getInstance(){
if(commonHashtable == null)
commonHashtable = new Hashtable<String, Object>();
return commonHashtable;
}
on getInstance(), it returns a commonHashtable which can be used to store values temporarily!
so, add this on addbutton click event
Hashtable hash = CommonHashtable.getInstance();
hash.put("NEW_STUDENT_NAME", et.getText().toString());
and add this in you onResume() of MainActivity
Hashtable hash = CommonHashtable.getInstance();
Object studentName = (String) hash.get("NEW_STUDENT_NAME");
if(studentName != null){
notifyArray();
}

Android Setting text from a getter method in another class

I've looked all over the place and taken all of the tips given, but my app still force closes.
The app has two classes (Main and Next) and "Next" class has a get method. When I try to use the get method in the "Main" class my app force closes. This is the line of code that causes the problems:
timesHit_txtview.setText(next.getTimesHit());
Like I mentioned before, I don't get any errors in eclipse. The First error I get from log cat is "Uncaught handler: thread main exiting due to uncaught exception"
Any suggestions? Thanks in advance
EDIT:
package com.whatever.main;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
Next next = new Next();
TextView timesHit_txtview = (TextView) findViewById(R.id.textView2);
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
timesHit_txtview.setText(5);
Button next_btn = (Button) findViewById(R.id.button1);
next_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent nextscreen_intent = new Intent(view.getContext(), Next.class);
startActivityForResult(nextscreen_intent, 0);
}
});
}
}
You're trying to initialize a widget before the onCreate() call has been completed.
Initialize your TextView in the onCreate() method before you call setText on it, like so:
public class MainActivity extends Activity {
Next next;
TextView timesHit_txtview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
next = new Next(); // Initialize Next
timesHit_txtview = (TextView) findViewById(R.id.textView2); // Initialize Widget
timesHit_txtview.setText(5);
Button next_btn = (Button) findViewById(R.id.button1);
next_btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent nextscreen_intent = new Intent(view.getContext(), Next.class);
startActivityForResult(nextscreen_intent, 0);
}
});
}
In your current code, timesHit_txtview is null when you try to set a text for it, which makes you Activity crash.

Categories

Resources