Android development beginner - error - android

Well, I'm doing this app just for trial. And there's this error. It says:
04-21 04:11:41.618: E/AndroidRuntime(333): FATAL EXCEPTION: main
04-21 04:11:41.618: E/AndroidRuntime(333): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.windteste/com.example.windteste.MainActivity}: java.lang.NullPointerException
04-21 04:11:41.618: E/AndroidRuntime(333): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
04-21 04:11:41.618: E/AndroidRuntime(333): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-21 04:11:41.618: E/AndroidRuntime(333): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
..and a lot more lines of error. So, these are the two methods (Dfig and MainActivity):
package com.example.windteste;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Dfig extends Activity{
#Override
protected void onCreate(Bundle blablu) {
// TODO Auto-generated method stub
super.onCreate(blablu);
setContentView(R.layout.activity_main);
MediaPlayer windsound = MediaPlayer.create(Dfig.this, R.raw.windsound);
windsound.start();
Thread timer = new Thread(){
public void run(){
try{
sleep(4000);
}catch (InterruptedException e){
e.printStackTrace();
}finally{
Intent openMain = new Intent("com.example.windteste.MAIN");
startActivity(openMain);
}
}
};
timer.start();
windsound.release();
}
}
package com.example.windteste;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.Activity;
import android.text.InputType;
----------------------------------------------------------------------------------
public class MainActivity extends Activity {
Button check = (Button) findViewById(R.id.calculator);
final EditText UserInput = (EditText) findViewById(R.id.windspeed);
final TextView P = (TextView) findViewById(R.id.potencia);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout2);
UserInput.setInputType(InputType.TYPE_CLASS_NUMBER);
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Number Ws = (Number) UserInput.getText();
P.setText("Your total is " + Ws);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Well, I hope you can help me.
Thank you!

Try:
public class MainActivity extends Activity {
Button check;
final EditText UserInput;
final TextView P;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout2);
check = (Button) findViewById(R.id.calculator);
UserInput = (EditText) findViewById(R.id.windspeed);
P = (TextView) findViewById(R.id.potencia);
//Rest is same
You cannot use findViewById() until after setContentView() has been called.

Make sure both the activities are listed in the manifest. What it looks like is MainActivity is not listed in your manifest file.

Related

Testing Android app: Exception during suite construction

I have a simple application that I'm trying to test. It has two activities and two buttons (each button goes to the other activity - MainActivity and MainActivity2), and I'm trying to make some simple Robotium tests of it. I am getting the following error:
java.lang.RuntimeException: Exception during suite construction at
android.test.suitebuilder.TestSuiteBuilder$FailedToCreateTests.testSuiteConstructionFailed(TestSuiteBuilder.java:238)
at java.lang.reflect.Method.invokeNative(Native Method) at
android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191) at
android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176) at
android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554)
at
android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1840)
Caused by: java.lang.reflect.InvocationTargetException at
java.lang.reflect.Constructor.constructNative(Native Method) at
java.lang.reflect.Constructor.newInstance(Constructor.java:423) at
android.test.suitebuilder.TestMethod.instantiateTest(TestMethod.java:87)
at android.test.suitebuilder.TestMethod.createTest(TestMethod.java:73)
at
android.test.suitebuilder.TestSuiteBuilder.addTest(TestSuiteBuilder.java:262)
at
android.test.suitebuilder.TestSuiteBuilder.build(TestSuiteBuilder.java:184)
at
android.test.InstrumentationTestRunner.onCreate(InstrumentationTestRunner.java:379)
at
android.app.ActivityThread.handleBindApplication(ActivityThread.java:5142)
at android.app.ActivityThread.access$1500(ActivityThread.java:156) at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1418)
at android.os.Handler.dispatchMessage(Handler.java:102) at
android.os.Looper.loop(Looper.java:157) at
android.app.ActivityThread.main(ActivityThread.java:5872) at
java.lang.reflect.Method.invokeNative(Native Method) at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674) at
dalvik.system.NativeStart.main(Native Method) Caused by:
java.lang.NullPointerException at
android.view.ViewConfiguration.get(ViewConfiguration.java:338) at
android.view.View.(View.java:3490) at
android.view.View.(View.java:3547) at
android.widget.TextView.(TextView.java:674) at
android.widget.Button.(Button.java:107) at
android.widget.CompoundButton.(CompoundButton.java:68) at
android.widget.CheckBox.(CheckBox.java:68) at
android.widget.CheckBox.(CheckBox.java:64) at
android.widget.CheckBox.(CheckBox.java:60) at
com.example.twoactivities.test.RobotiumTest1.(RobotiumTest1.java:19)
... 18 more
I've tried everything I can find, and none of those solutions work for me. (No parameters in constructor, checking build path to ensure JARs are in the right place, ensuring that my application under test is "debuggable", etc.)
My code is here:
package com.example.twoactivities.test;
import com.example.twoactivities.*;
import com.robotium.solo.Solo;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.CheckBox;
import android.widget.CheckBox;
import android.app.Activity;
public class RobotiumTest1 extends ActivityInstrumentationTestCase2<MainActivity> {
private Solo solo;
public RobotiumTest1() {
super(MainActivity.class);
}
#Override
public void setUp() throws Exception {
//setUp() is run before a test case is started.
//This is where the solo object is created.
solo = new Solo(getInstrumentation(), getActivity());
}
// #Override
// public void tearDown() throws Exception {
// //tearDown() is run after a test case has finished.
// //finishOpenedActivities() will finish all the activities that have been opened during the test execution.
// solo.finishOpenedActivities();
// }
public void testClickButton() throws Exception{
solo.assertCurrentActivity("Expected to be on MainActivity activity", "MainActivity.class");
solo.clickOnButton("Go to page 2");
solo.assertCurrentActivity("Not on Activity 2", MainActivity2.class);
solo.clickOnButton("Go to page 1");
solo.assertCurrentActivity("Not on Activity 1", MainActivity.class);
}
}
Any ideas how I can get this test to run?
Thanks,
Stephanie
EDIT:
MainActivity
package com.example.twoactivities;
import com.example.twoactivities.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
public class MainActivity extends Activity {
final CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox1);
final TextView text2 = (TextView) findViewById(R.id.checkBoxTextView);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void activity2(View view){
Intent intent = new Intent(this,com.example.twoactivities.MainActivity2.class);
startActivity(intent);
}
public void onCheckBoxClicked(View view){
if (checkBox.isChecked()) {
text2.setText("Checked");
}
else {
((TextView) findViewById(R.id.checkBoxTextView)).setText("Unchecked");
}
}
}
MainActivity2
package com.example.twoactivities;
import com.example.twoactivities.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
public void activity1(View view){
Intent intent = new Intent(this,com.example.twoactivities.MainActivity.class);
startActivity(intent);
}
}
I actually haven't changed anything (I don't think) since it last ran successfully.
Sept 12 edits:
"solo" object was being initialized after I was trying to use it.
package com.example.twoactivities.test;
import com.example.twoactivities.*;
import com.example.twoactivities.R;
import com.robotium.solo.Solo;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.CheckBox;
import android.widget.TextView;
public class RobotiumTest1 extends ActivityInstrumentationTestCase2<MainActivity> {
public Solo solo;
private TextView checkBoxText;
public CheckBox checkBox1 ;
public RobotiumTest1() {
super(MainActivity.class);
}
#Override
public void setUp() throws Exception {
//setUp() is run before a test case is started.
//This is where the solo object is created.
solo = new Solo(getInstrumentation(), getActivity());
checkBoxText = (TextView) getActivity().findViewById(R.id.checkBoxTextView);
checkBox1 = (CheckBox) getActivity().findViewById(R.id.checkBox1);
}
public void testClickButton() throws Exception{
solo.assertCurrentActivity("Expected to be on MainActivity activity", "MainActivity");
solo.clickOnButton("Go to page 2");
solo.assertCurrentActivity("Not on Activity 2", MainActivity2.class);
solo.clickOnButton("Go to page 1");
solo.assertCurrentActivity("Not on Activity 1", MainActivity.class);
}
The clue is in the log you posted.
Caused by: java.lang.NullPointerException
at android.view.ViewConfiguration.get(ViewConfiguration.java:338)
at android.view.View.(View.java:3490)
at android.view.View.(View.java:3547)
at android.widget.TextView.(TextView.java:674)
at android.widget.Button.(Button.java:107)
at android.widget.CompoundButton.(CompoundButton.java:68)
at android.widget.CheckBox.(CheckBox.java:68)
at android.widget.CheckBox.(CheckBox.java:64)
at android.widget.CheckBox.(CheckBox.java:60) at com.example.twoactivities.test.RobotiumTest1.(RobotiumTest1.java:19) ... 18 more
You have a NullPointerException causing you the issues, this NullPointerException is in your applications code not the code posted here however (Note if you add it, I will look into it here for you)
EDIT
The code below is the issue:
public class MainActivity extends Activity {
final CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox1);
final TextView text2 = (TextView) findViewById(R.id.checkBoxTextView);
The problem is you are trying to find views that do not actually exist until onCreate() is called so these will be null. move the initialisation of these to onCreate() and you should be ok.
Next edit to answer your question in comments.
Ok so now we are away from Robotium and in to core Java, the issue you have now is scope, the thing is where you declare a variable and it is accesible is different to where you instantiate it. You can declare the variables existance in the same scope as you are currently but instantiate it in onCreate().
package com.example.twoactivities;
import com.example.twoactivities.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
public class MainActivity extends Activity {
final CheckBox checkBox;
final TextView text2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkBox = (CheckBox) findViewById(R.id.checkBox1);
text2 = (TextView) findViewById(R.id.checkBoxTextView);
}
public void activity2(View view){
Intent intent = new Intent(this,com.example.twoactivities.MainActivity2.class);
startActivity(intent);
}
public void onCheckBoxClicked(View view){
if (checkBox.isChecked()) {
text2.setText("Checked");
}
else {
((TextView) findViewById(R.id.checkBoxTextView)).setText("Unchecked");
}
}
}

Android error that i can't understand. Can someone help me?

I have built a sql database and i have implement the searchview widget to ba able to use in android pre API 11
When i try to do a research, the application close itself and i get this error and other messages:
Error
08-19 15:15:25.560: E/dalvikvm(6838): Could not find class 'android.support.v7.widget.SearchView$5', referenced from method android.support.v7.widget.SearchView.addOnLayoutChangeListenerToDropDownAnchorSDK11
08-19 15:15:25.560: I/dalvikvm(6838): Failed resolving Landroid/support/v7/widget/SearchView$5; interface 814 'Landroid/view/View$OnLayoutChangeListener;'
08-19 15:15:25.560: W/dalvikvm(6838): Link of class 'Landroid/support/v7/widget/SearchView$5;' failed
08-19 15:15:25.560: D/dalvikvm(6838): VFY: replacing opcode 0x22 at 0x0002
08-19 15:15:25.560: D/dalvikvm(6838): VFY: dead code 0x0004-000a in Landroid/support/v7/widget/SearchView;.addOnLayoutChangeListenerToDropDownAnchorSDK11 ()V
I don't know if is something wrong with my code or else.
There's someone can help me?
Thank you
i think the error is here
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.ListView;
public class SearchableActivity extends ListActivity{
DatabaseTable db = new DatabaseTable(this);
final Context context=this;
ListView list;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
list=(ListView)findViewById(android.R.id.list);
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleIntent(getIntent());
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
Cursor c = db.getWordMatches(query, null);
c.moveToFirst();
}
}
}
I have tried to import android.support.v7.widget.Searchview, but it says that is never used, and the error doesn't disappear. for this project, i have created the MainActivity.Java, wich contain the SearchWidget, a DatabaseTable.java a definitions.txt wich contains the data, a Search.xml and a SearchActivity.Java (the code below), i have also put the meta tag in the MainActivity and in the SearchActivity, inside the Manifest, don't know if can bel Helpfull to insert here the code of every page...I really don't know what to do anymore !!
Sure, here's the code of my main activity
import android.os.Bundle;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.SearchView;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends ActionBarActivity implements OnClickListener{
ActionBar actionBar;
Button a;
Button b;
Button c;
Button d;
Button e;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
actionBar = getSupportActionBar();
actionBar.setTitle("Trial");
initialiseOnClick();
a.setOnClickListener(this);
b.setOnClickListener(this);
c.setOnClickListener(this);
d.setOnClickListener(this);
e.setOnClickListener(this);
}
//START SEARCHVIEWWIDGET
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
// Configure the search info and add any event listeners
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(true);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_search:
onSearchRequested();
return true;
default:
return false;
}
}
// END SEARCHVIEWWIDGET
private void initialiseOnClick() {
// TODO Auto-generated method stub
a = (Button) findViewById (R.id.button_a);
b = (Button) findViewById (R.id.button_b);
c = (Button) findViewById (R.id.button_c);
d = (Button) findViewById (R.id.button_d);
e = (Button) findViewById (R.id.button_e);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.button_a:
Intent a = new Intent(MainActivity.this, EuropeActivity.class);
startActivity(a);
break;
case R.id.button_b:
Intent b = new Intent(MainActivity.this, AmericasActivity.class);
startActivity(b);
break;
case R.id.button_c:
Intent c = new Intent(MainActivity.this, AsiaActivity.class);
startActivity(c);
break;
case R.id.button_d:
Intent d = new Intent(MainActivity.this, OceaniaActivity.class);
startActivity(d);
break;
case R.id.button_e:
Intent e = new Intent(MainActivity.this, AfricaActivity.class);
startActivity(e);
break;
}
}
}

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();
}

I can't setText() in another class in android

I have a TextView with the id android:id="#+id/yazi", and I have a button that has build in android:OnClick="gonderB"
and I can complie this code:
package com.seri.bir;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
Bilmez b;
TextView t;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = new Bilmez();
t = (TextView) findViewById(R.id.yazi);
}
public void gonderB (View v,TextView t,Bilmez b){
String s = " ..."+this;
b.yaziYaz(v,s,t);
}
}
class Bilmez {
public void yaziYaz(View v,String s,TextView t){
t.setText(s);
}
}
However I have an error.
Can I setText in another class?
You can overwrite onClick of the activity. Avoid the using of the android:OnClick="gonderB" line in the xml file. I think it is better to implement the onClickListener and attach it to View Objects within your code.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
Bilmez b;
TextView t;
Button bt;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = new Bilmez();
t = (TextView) findViewById(R.id.yazi);
Button bt = (Button) findViewById(R.id.btn);
bt.setOnClickListener(this);
}
#Override
public void onClick(View clickedView) {
switch (clickedView.getId()) {
case R.id.btn:
String s = "...." + this;
b.changeText(t,s);
break;
}} //end of main class }
In the changeText method you change the text of the TextView. This method can if be placed in another class if you like that.
class Bilmez {
public void changeText(TextView t, String s){
t.setText(s);
}
}
Perhaps what you are experiencing is a need to run the function on the UI thread?
public void yaziYaz(View v,final String s,final TextView t) {
runOnUiThread(new Runnable() {
public void run() {
t.setText(s);
}
});
}
i think you should do that:
public void gonderB (new View v,TextView t,Bilmez b){
String s = " ..."+this;
b.yaziYaz(v,s,t);
}

The application just "stop unexpectedly" when run on the phone

When I run my application on the emulator, it run right and no problem happens. But when I run it on the phone, a problem appear "stop unexpectedly".
In my application:
The main activity (Background) can exchange to 4 activities: LivingRoom, DiningRoom, Wc, Garage. The problem "stop unexpectedly" just happens when i try to go to the DiningRoom activity.
This is my code :
1.Background
package com.example.background;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import at.abraxas.amarino.Amarino;
public class BackgroundActivity extends Activity {
private Button Wc, Dining_Room, Living_Room, Garage;
private Intent D_intent, L_intent, G_intent, W_intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Amarino.connect(this, DEVICE_ADDRESS);
Living_Room = (Button) findViewById(R.id.living);
//Living_Room.setBackgroundColor(Color.TRANSPARENT);
Living_Room.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
L_intent = new Intent(view.getContext(), LivingRoom.class);
startActivityForResult(L_intent, 0);
}
});
Dining_Room = (Button) findViewById(R.id.dining);
// Dining_Room.setBackgroundColor(Color.TRANSPARENT);
Dining_Room.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
D_intent = new Intent(view.getContext(), DiningRoom.class);
startActivityForResult(D_intent, 0);
}
});
Wc = (Button) findViewById(R.id.wc);
//Wc.setBackgroundColor(Color.TRANSPARENT);
Wc.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
W_intent = new Intent(view.getContext(), Wc.class);
startActivityForResult(W_intent, 0);
}
});
Garage = (Button) findViewById(R.id.garage);
// Garage.setBackgroundColor(Color.TRANSPARENT);
Garage.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
G_intent = new Intent(view.getContext(), Garage.class);
startActivityForResult(G_intent, 0);
}
});
}
}
2.DiningRoom
package com.example.background;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.ToggleButton;
import at.abraxas.amarino.Amarino;
public class DiningRoom extends Activity implements OnCheckedChangeListener, OnSeekBarChangeListener{
private static final String DEVICE_ADDRESS = "00:06:66:43:9B:56";
final int DELAY = 150;
ToggleButton button;
SeekBar seekbar1;
SeekBar seekbar2;
boolean light2;
int light1;
int fan;
long lastchange;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.diningroom);
//back ve trang chinh
Button backhome = (Button) findViewById(R.id.D_backhome);
backhome.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});
Amarino.connect(this, DEVICE_ADDRESS);
button = (ToggleButton) findViewById(R.id.Dbutton);
seekbar1 = (SeekBar) findViewById(R.id.Dseekbar1);
seekbar2 = (SeekBar) findViewById(R.id.Dseekbar2);
button.setOnCheckedChangeListener(this);
seekbar1.setOnSeekBarChangeListener(this);
seekbar2.setOnSeekBarChangeListener(this);
}
//---START----------------------------------------------------------------------------------------------
#Override
protected void onStart(){
super.onStart();
// load last state
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
light2 = pref.getBoolean("light2", true);
light1 = pref.getInt("light1", 0);
fan = pref.getInt("fan", 0);
button.setChecked(light2);
seekbar1.setProgress(light1);
seekbar2.setProgress(fan);
new Thread(){
public void run(){
try{
Thread.sleep(6000);
}catch (InterruptedException e) {}
update_light2();
update_light1_fan();
}
}.start();
}
//STOP--------------------------------------------------------------------------------
#Override
protected void onStop(){
super.onStop();
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putBoolean("light2", light2)
.putInt("light1", light1)
.putInt("fan", fan)
.commit();
Amarino.disconnect(this, DEVICE_ADDRESS);
}
//UPDATE LIGHT2--------------------------------------------------------------------------------
private void Update_Light2_State(final CompoundButton button){
light2 = button.isChecked();
update_light2();
}
private void update_light2(){
int a;
a = (light2 == true)? 255:0;
Amarino.sendDataToArduino(this, DEVICE_ADDRESS, 'o', a);
}
//UPDATE LIGHT1 FAN-------------------------------------------------------------------------------------
private void Update_Light1_Fan_State(final SeekBar seekbar){
switch (seekbar.getId()){
case R.id.Dseekbar1:
light1 = seekbar.getProgress();
update_light1();
break;
case R.id.Dseekbar2:
fan = seekbar.getProgress();
update_fan();
break;
}
}
private void update_light1_fan(){
update_light1();
update_fan();
}
private void update_light1(){
Amarino.sendDataToArduino(this, DEVICE_ADDRESS, 'p', light1);
}
private void update_fan(){
Amarino.sendDataToArduino(this, DEVICE_ADDRESS, 'q', fan);
}
//---TRACE--------------------------------------------------------------------------------------
#Override
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
if (System.currentTimeMillis() - lastchange > DELAY ){
Update_Light2_State(button);
lastchange = System.currentTimeMillis();
}
}
#Override
public void onProgressChanged(SeekBar seekbar, int progress, boolean fromUser) {
if (System.currentTimeMillis() - lastchange > DELAY ){
Update_Light1_Fan_State(seekbar);
lastchange = System.currentTimeMillis();
}
}
#Override
public void onStartTrackingTouch(SeekBar seekbar) {
lastchange = System.currentTimeMillis();
}
#Override
public void onStopTrackingTouch(SeekBar seekbar) {
Update_Light1_Fan_State(seekbar);
}
}
3.Logcat
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.background/com.example.background.DiningRoom}: java.lang.ClassCastException:
java.lang.Boolean
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2669)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2685)
at android.app.ActivityThread.access$2300(ActivityThread.java:126)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2038)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:4633)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: java.lang.Boolean
at android.app.ContextImpl$SharedPreferencesImpl.getInt(ContextImpl.java:2721)
at com.example.background.DiningRoom.onStart(DiningRoom.java:80)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1129)
at android.app.Activity.performStart(Activity.java:3781)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2642)
... 11 more
Force finishing activity com.example.background/.DiningRoom
Force finishing activity com.example.background/.BackgroundActivity
I also try to wrote another application similar to the above application. But I just have only 1 sub activity: DiningRoom, then it ran well on the phone.
The Background when I just have one sub activity
[CODE]
public class Test1Activity extends Activity {
private Button Dining_Room;
private Intent D_intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Dining_Room = (Button) findViewById(R.id.dining);
// Dining_Room.setBackgroundColor(Color.TRANSPARENT);
Dining_Room.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
D_intent = new Intent(view.getContext(), Dining.class);
startActivityForResult(D_intent, 0);
}
});
}
}
[/CODE]
Careful reading of logcat reveals that:
Caused by: java.lang.ClassCastException: java.lang.Boolean
at android.app.ContextImpl$SharedPreferencesImpl.getInt(ContextImpl.java:2721)
at com.example.background.DiningRoom.onStart(DiningRoom.java:80)
This means, that shared preference was boolean instead of int on line 80.
PS: I develop lightweight dependency injection framework for android, and it already covers
loading / saving preferences. Just grab it here:
https://github.com/ko5tik/andject
I would guess that the value "light1" in your shared preferences was not saved as an integer (but as a boolean).
From the docs:
Throws ClassCastException if there is a preference with this name that
is not an int.

Categories

Resources