Unable to instantiate activity Android - java

Hello I am just getting started in Android. Help please, read all posts about this, nothing cant help. Tried all combinations naming activities in manifest. This app showing lifecycle of the app.
Log
02-11 01:07:36.538: W/dalvikvm(20921): threadid=1: thread exiting with uncaught exception (group=0x40ab6228)
02-11 01:07:36.558: E/AndroidRuntime(20921): FATAL EXCEPTION: main
02-11 01:07:36.558: E/AndroidRuntime(20921): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.lab1/com.example.lab1.MainActivity}: java.lang.NullPointerException
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2240)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.app.ActivityThread.access$600(ActivityThread.java:139)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1262)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.os.Handler.dispatchMessage(Handler.java:99)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.os.Looper.loop(Looper.java:156)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.app.ActivityThread.main(ActivityThread.java:4977)
02-11 01:07:36.558: E/AndroidRuntime(20921): at java.lang.reflect.Method.invokeNative(Native Method)
02-11 01:07:36.558: E/AndroidRuntime(20921): at java.lang.reflect.Method.invoke(Method.java:511)
02-11 01:07:36.558: E/AndroidRuntime(20921): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
02-11 01:07:36.558: E/AndroidRuntime(20921): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
02-11 01:07:36.558: E/AndroidRuntime(20921): at dalvik.system.NativeStart.main(Native Method)
02-11 01:07:36.558: E/AndroidRuntime(20921): Caused by: java.lang.NullPointerException
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.content.ContextWrapper.getResources(ContextWrapper.java:81)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.view.View.<init>(View.java:2723)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.view.View.<init>(View.java:2771)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.widget.TextView.<init>(TextView.java:504)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.widget.TextView.<init>(TextView.java:494)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.widget.TextView.<init>(TextView.java:489)
02-11 01:07:36.558: E/AndroidRuntime(20921): at com.example.lab1.MainActivity.<init>(MainActivity.java:30)
02-11 01:07:36.558: E/AndroidRuntime(20921): at java.lang.Class.newInstanceImpl(Native Method)
02-11 01:07:36.558: E/AndroidRuntime(20921): at java.lang.Class.newInstance(Class.java:1319)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.app.Instrumentation.newActivity(Instrumentation.java:1039)
02-11 01:07:36.558: E/AndroidRuntime(20921): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
02-11 01:07:36.558: E/AndroidRuntime(20921): ... 11 more
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lab1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="ActivityTwo"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
MainActivity
package com.example.lab1;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String RESTART_KEY = "restart";
private static final String RESUME_KEY = "resume";
private static final String START_KEY = "start";
private static final String CREATE_KEY = "create";
// String for LogCat documentation
private final static String TAG = "Lab-ActivityOne";
// Lifecycle counters
// TODO:
int mCreate=0;
int mResume=0;
int mRestart=0;
int mStart=0;
TextView textView1 = new TextView(this);
TextView textView2 = new TextView(this);
TextView textView3 = new TextView(this);
TextView textView4 = new TextView(this);
// TODO: Create variables for each of the TextViews, called
// mTvCreate, etc.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_one);
// TODO: Assign the appropriate TextViews to the TextView variables
// Hint: Access the TextView by calling Activity's findViewById()
textView1 = (TextView) findViewById(R.id.create);
textView2 = (TextView) findViewById(R.id.start);
textView3 = (TextView) findViewById(R.id.resume);
textView4 = (TextView) findViewById(R.id.restart);
Button launchActivityTwoButton = new Button(this);
launchActivityTwoButton = (Button) findViewById(R.id.bLaunchActivityTwo);
launchActivityTwoButton.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View view)
{
// TODO:
// Launch Activity Two
// Hint: use Context's startActivity() method
// Create an intent stating which Activity you would like to start
// Launch the Activity using the intent
Intent myIntent=new Intent(view.getContext(),ActivityTwo.class);
startActivity(myIntent);
}
});
// Check for previously saved state
if (savedInstanceState != null) {
mCreate=savedInstanceState.getInt(CREATE_KEY);
mResume=savedInstanceState.getInt(RESUME_KEY);
mRestart=savedInstanceState.getInt(RESTART_KEY);
mStart=savedInstanceState.getInt(START_KEY);
}
// TODO: Emit LogCat message
Log.i(TAG,"OnCreate");
// TODO:
mCreate++;
//displayCounts();
}
// Lifecycle callback overrides
#Override
public void onStart() {
super.onStart();
// TODO: Emit LogCat message
Log.i(TAG,"OnStart");
// TODO:
mStart++;
//displayCounts();
}
#Override
public void onResume() {
super.onResume();
// TODO: Emit LogCat message
Log.i(TAG,"OnResume");
// TODO:
mResume++;
displayCounts();
}
#Override
public void onPause() {
super.onPause();
// TODO: Emit LogCat message
Log.i(TAG,"OnPause");
}
#Override
public void onStop() {
super.onStop();
// TODO: Emit LogCat message
Log.i(TAG,"OnStop");
}
#Override
public void onRestart() {
super.onRestart();
// TODO: Emit LogCat message
Log.i(TAG,"OnRestart");
// TODO:
mRestart++;
displayCounts();
}
#Override
public void onDestroy() {
super.onDestroy();
// TODO: Emit LogCat message
Log.i(TAG,"OnDestroy");
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// TODO:
// Save state information with a collection of key-value pairs
// 4 lines of code, one for every count variable
savedInstanceState.putInt(RESTART_KEY,mRestart);
savedInstanceState.putInt(RESUME_KEY,mResume);
savedInstanceState.putInt(START_KEY,mStart);
savedInstanceState.putInt(CREATE_KEY,mCreate);
}
// Updates the displayed counters
public void displayCounts() {
textView1.setText("onCreate() calls: " + mCreate);
textView2.setText("onStart() calls: " + mStart);
textView3.setText("onResume() calls: " + mResume);
textView4.setText("onRestart() calls: " + mRestart);
}
}
ActivityTwo
package com.example.lab1;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class ActivityTwo extends Activity {
private static final String RESTART_KEY = "restart";
private static final String RESUME_KEY = "resume";
private static final String START_KEY = "start";
private static final String CREATE_KEY = "create";
// String for LogCat documentation
private final static String TAG = "Lab-ActivityTwo";
// Lifecycle counters
// TODO:
int mCreate=0;
int mResume=0;
int mRestart=0;
int mStart=0;
TextView textView1 = new TextView(this);
TextView textView2 = new TextView(this);
TextView textView3 = new TextView(this);
TextView textView4 = new TextView(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_two);
textView1 = (TextView) findViewById(R.id.create);
textView2 = (TextView) findViewById(R.id.start);
textView3 = (TextView) findViewById(R.id.resume);
textView4 = (TextView) findViewById(R.id.restart);
Button closeButton = new Button(this);
closeButton= (Button) findViewById(R.id.bClose);
closeButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
// Check for previously saved state
if (savedInstanceState != null) {
// TODO:
// Restore value of counters from saved state
// Only need 4 lines of code, one for every count variable
mCreate=savedInstanceState.getInt(CREATE_KEY);
mResume=savedInstanceState.getInt(RESUME_KEY);
mRestart=savedInstanceState.getInt(RESTART_KEY);
mStart=savedInstanceState.getInt(START_KEY);
}
// TODO: Emit LogCat message
// TODO: Emit LogCat message
Log.i(TAG,"OnCreate");
// TODO:
mCreate++;
displayCounts();
// TODO:
// Update the appropriate count variable
// Update the user interface via the displayCounts() method
}
// Lifecycle callback methods overrides
#Override
public void onStart() {
super.onStart();
// TODO: Emit LogCat message
// TODO:
// Update the appropriate count variable
// Update the user interface
// TODO: Emit LogCat message
Log.i(TAG,"OnStart");
// TODO:
mStart++;
displayCounts();
}
#Override
public void onResume() {
super.onResume();
// TODO: Emit LogCat message
// TODO:
// Update the appropriate count variable
// Update the user interface
Log.i(TAG,"OnResume");
// TODO:
mResume++;
displayCounts();
}
#Override
public void onPause() {
super.onPause();
// TODO: Emit LogCat message
Log.i(TAG,"OnPause");
}
#Override
public void onStop() {
super.onStop();
// TODO: Emit LogCat message
Log.i(TAG,"OnStop");
}
#Override
public void onRestart() {
super.onRestart();
// TODO: Emit LogCat message
Log.i(TAG,"OnRestart");
// TODO:
mRestart++;
displayCounts();
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG,"OnDestroy");
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// TODO:
savedInstanceState.putInt(RESTART_KEY,mRestart);
savedInstanceState.putInt(RESUME_KEY,mResume);
savedInstanceState.putInt(START_KEY,mStart);
savedInstanceState.putInt(CREATE_KEY,mCreate);
}
// Updates the displayed counters
public void displayCounts() {
textView1.setText("onCreate() calls: " + mCreate);
textView2.setText("onStart() calls: " + mStart);
textView3.setText("onResume() calls: " + mResume);
textView4.setText("onRestart() calls: " + mRestart);
}
}

I am a bit new to this myself so I could be talking rubbish....
I would get rid of the member initialisation on textView1 -> textView4 and move it until after the setContentView. Next I would place a breakpoint on super.OnCreate and see if it gets there. If you do single step every line you can until you see the null pointer.

Related

setOnItemSelectedListener makes my app crash

I am trying to use a Spinner to select a user name and then open a new conversation layout when the client clicks the start chat button. I am sure that the button code is correct but my spinner cause my application crash.
myListView.setOnItemSelectedListener(new OnItemSelectedListener () {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
name1 = parent.getItemAtPosition(pos).toString();
CStart = (Button) findViewById(R.id.Start) ;
CStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
open(v);
}
});
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
});
The open method:
protected void open(View v) {
Intent i = new Intent(this, MainActivity2.class);
i.putExtra("message", name1);
startActivityForResult(i, 1);
}
Can you help me to fix my code?
Logcat :
03-24 19:48:32.967: E/AndroidRuntime(23058): FATAL EXCEPTION: main
03-24 19:48:32.967: E/AndroidRuntime(23058): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.javachat/com.example.javachat.MainActivity}: java.lang.IllegalArgumentException: Receiver not registered: com.example.javachat.MainActivity$1#418afa30
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.app.ActivityThread.access$600(ActivityThread.java:162)
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.os.Handler.dispatchMessage(Handler.java:107)
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.os.Looper.loop(Looper.java:194)
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.app.ActivityThread.main(ActivityThread.java:5371)
03-24 19:48:32.967: E/AndroidRuntime(23058):at java.lang.reflect.Method.invokeNative(Native Method)
03-24 19:48:32.967: E/AndroidRuntime(23058):at java.lang.reflect.Method.invoke(Method.java:525)
03-24 19:48:32.967: E/AndroidRuntime(23058):at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833) 03-24 19:48:32.967: E/AndroidRuntime(23058):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
03-24 19:48:32.967: E/AndroidRuntime(23058):at dalvik.system.NativeStart.main(Native Method)
03-24 19:48:32.967: E/AndroidRuntime(23058): Caused by: java.lang.IllegalArgumentException: Receiver not registered: com.example.javachat.MainActivity$1#418afa30
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:657)
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.app.ContextImpl.unregisterReceiver(ContextImpl.java:1442)
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:445) 03-24 19:48:32.967: E/AndroidRuntime(23058): at com.example.javachat.MainActivity.onDestroy(MainActivity.java:229)
03-24 19:48:32.967: E/AndroidRuntime(23058):at com.example.javachat.MainActivity.onCreate(MainActivity.java:136)
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.app.Activity.performCreate(Activity.java:5122)
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1084)
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
03-24 19:48:32.967: E/AndroidRuntime(23058):... 11 more
manifest code :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.javachat"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity2" />
</application>
</manifest>
my .java file if you need to check any thing else like imports and methods....
package com.example.javachat;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 1;
private Button onBtn;
private Button offBtn;
private Button listBtn;
private Button findBtn;
private TextView text;
private Button CStart ;
private String name1 ;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private Spinner myListView;
private ArrayAdapter<String> BTArrayAdapter;
//*******************************MAIN************************
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
// take an instance of BluetoothAdapter - Bluetooth radio
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter == null) {
onBtn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
CStart.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
text = (TextView) findViewById(R.id.text);
onBtn = (Button)findViewById(R.id.turnOn);
onBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
on(v);
}
});
offBtn = (Button)findViewById(R.id.turnOff);
offBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
off(v);
}
});
//*********************************************************
listBtn = (Button)findViewById(R.id.paired);
listBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
});
//**********************************************************
myListView.setOnItemSelectedListener(new OnItemSelectedListener (){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
name1= new String (parent.getItemAtPosition(pos).toString());
CStart = (Button) findViewById(R.id.Start) ;
CStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
open(v);
}
});
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
Toast.makeText(getApplicationContext(),"Select a device" ,
Toast.LENGTH_LONG).show();
}
});
//***********************************************************
findBtn = (Button)findViewById(R.id.search);
findBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
//***********************************************************
myListView = (Spinner)findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
BTArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
myListView.setAdapter(BTArrayAdapter);
}
}
//**********************************METHODE***********************
protected void open(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(this ,MainActivity2.class);
// i.putExtra("message",name1);
startActivityForResult(i, 1);
}
public void on(View view){
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(),"Bluetooth turned on" ,
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),"Bluetooth is already on",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
if(myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");
}
}
}
public void list(View view){
// get paired devices
pairedDevices = myBluetoothAdapter.getBondedDevices();
// put it's one to the adapter
for(BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());
Toast.makeText(getApplicationContext(),"Show Paired Devices",
Toast.LENGTH_SHORT).show();
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name and the MAC address of the object to the arrayAdapter
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
public void off(View view){
myBluetoothAdapter.disable();
text.setText("Status: Disconnected");
Toast.makeText(getApplicationContext(),"Bluetooth turned off",
Toast.LENGTH_LONG).show();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(bReceiver);
}
}
Exception clearly states the following:
Receiver not registered: com.example.javachat.MainActivity$1#418afa30
Crash happens here:
03-24 19:48:32.967: E/AndroidRuntime(23058):at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:445)
03-24 19:48:32.967: E/AndroidRuntime(23058): at com.example.javachat.MainActivity.onDestroy(MainActivity.java:229)
03-24 19:48:32.967: E/AndroidRuntime(23058):at com.example.javachat.MainActivity.onCreate(MainActivity.java:136)
You have unregisterReceiver at the onDestroy, but you have no place, where you are registering it. Also you would like to take a look here, because onItemSelected will be called for Spinner without user action.
But it is not the end. The BroadcastReceiver declaration is wrong. Since you are using broadcast receiver locally, binding it to the Activity lifecycle, you should use LocalBroadcastManager, to register/unregister at the onCreate/onDestroy (or other lifecycle callbacks, depends on your needs). Thus, the following declaration in manifest makes no sense:
<receiver android:name=".bReceiver">
</receiver>
Because you have no class called bReceiver, you have a local variable (which should be actually made a class member) bReceiver, which points to an instance of BroadcastReceiver class.
if clicking on the Button is causing your crash, then the reason is -
you have set a method local anonymous inner class object as listener in your onItemSlected(). that object will be destroyed when the method execution is finished.
So when the onItemSelected is finished, your listener object is set properly. but by the time when button is being clicked, that saved listener object is invoked which is actually cleared by garbage collector.
you shouldn't set the listener this way. you can easily set the listener outside of your item click listener if I did understand your requirement correctly.

fatal error. launching activity in android

I want to access Confirmation activity from login activity. i was able to launch confirmation activity when i didn't have login and registration activity. login and registration works perfect without confirmation activity. and dashboard activity and confirmation activity works perfect without login and registration activity.
Registration Activity.
package com.example.androidhive;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.androidhive.library.DatabaseHandler;
import com.example.androidhive.library.UserFunctions;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RegisterActivity extends Activity {
Button btnRegister;
Button btnLinkToLogin;
EditText inputFullName;
EditText inputEmail;
EditText inputPassword;
TextView registerErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.registerName);
inputEmail = (EditText) findViewById(R.id.registerEmail);
inputPassword = (EditText) findViewById(R.id.registerPassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in registration
registerErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
// Close Registration View
finish();
}
});
}
}
Login Activity:-
import java.util.HashMap;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.androidhive.library.DatabaseHandler;
import com.example.androidhive.library.UserFunctions;
public class LoginActivity extends Activity {
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
Log.d("Button", "Login");
JSONObject json = userFunction.loginUser(email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});
}
}
Dashboard Activity:-
package com.example.androidhive;
import android.app.Activity;
import com.example.androidhive.ConfirmationActivity;
import com.example.androidhive.R;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Toast;
import android.widget.Button;
import com.example.androidhive.library.UserFunctions;
public class DashboardActivity extends Activity {
UserFunctions userFunctions;
Button btnLogout;
private String resultString="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/**
* Dashboard Screen for the application
* */
// Check login status in database
userFunctions = new UserFunctions();
if(userFunctions.isUserLoggedIn(getApplicationContext())){
setContentView(R.layout.dashboard);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnLogout.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
userFunctions.logoutUser(getApplicationContext());
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
});
}else{
// user is not logged in show login screen
Intent login = new Intent(getApplicationContext(), LoginActivity.class);
login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(login);
// Closing dashboard screen
finish();
}
}
public class WebAppInterface {
Context mContext;
/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}
/** Show a toast from the web page */
#JavascriptInterface
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==0)
if (resultCode == RESULT_OK) {
//Use Data to get string
resultString = data.getStringExtra("RESULT_STRING");
LaunchWebView(resultString);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void LaunchWebView(String resultString)
{
WebView engine=(WebView)findViewById(com.example.androidhive.R.id.web_engine);
//engine.getSettings().setJavaScriptEnabled(true);
String[] array=resultString.split(":");
engine.getSettings().setLoadsImagesAutomatically(true);
//engine.getSettings().setBuiltInZoomControls(true);
engine.getSettings().setUseWideViewPort(true);
engine.setWebChromeClient(new MyJavaScriptChromeClient());
engine.loadUrl("http://74.101.168.139/snapshot.cgi?user="+array[0]+"&pwd="+array[1]+"&count=0" + "&resolution=32"+ "&rate=6");
}
public void btnRefresh_ClicHandler(View view)
{
if(resultString!="")
LaunchWebView(resultString);
}
public void btnHome(View arg)
{
Intent intent=new Intent(this,ConfirmationActivity.class);
int result=0;
startActivityForResult(intent, result);
}
private class MyJavaScriptChromeClient extends WebChromeClient {
#Override
public boolean onJsAlert(WebView view, String url, String message,
JsResult result) {
// TODO Auto-generated method stub
return super.onJsAlert(view, null, message, result);
}
}
}
Confirmation Activity : -
package com.example.androidhive;
import com.example.androidhive.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class ConfirmationActivity extends Activity {
EditText txtPassword=null;
EditText txtUsername=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_confirmation);
}
public static final class menu2 {
public static final int confirmation=0x7f080000;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(menu2.confirmation, menu);
return true;
}
public void btnCancel_ClickHandler(View arg)
{
finish();
}
public void btnOk_ClickHandler(View arg)
{
txtUsername=(EditText)findViewById(com.example.androidhive.R.id.txtUserName);
txtPassword=(EditText)findViewById(com.example.androidhive.R.id.txtPassword);
if(txtUsername.getText().length()==0)
{
Toast.makeText(getApplicationContext(),
"User name can not be empty.", Toast.LENGTH_LONG).show();
return;
}
if(txtPassword.getText().length()==0)
{
Toast.makeText(getApplicationContext(),
"Password can not be empty.", Toast.LENGTH_LONG).show();
return;
}
Intent intent=new Intent();
intent.putExtra("RESULT_STRING",txtUsername.getText()+ ":"+txtPassword.getText());
setResult(RESULT_OK, intent);
finish();
}
}
Android Manifest.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.androidhive"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8"
android:targetSdkVersion="18"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:label="#string/app_name"
android:name=".DashboardActivity" >
</activity>
<!-- Confirmation Activity -->
<activity
android:label="Confiramtion Activity"
android:name=".ConfiramtionActivity"></activity>
<!-- Login Activity -->
<activity
android:label="Login Account"
android:name=".LoginActivity"></activity>
<!-- Register Activity -->
<activity
android:label="Register New Account"
android:name=".RegisterActivity">
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Android Fatal Error PLeaseeee Help:-
11-15 16:55:40.948: E/AndroidRuntime(858): FATAL EXCEPTION: main
11-15 16:55:40.948: E/AndroidRuntime(858): android.os.NetworkOnMainThreadException
11-15 16:55:40.948: E/AndroidRuntime(858): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
11-15 16:55:40.948: E/AndroidRuntime(858): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
11-15 16:55:40.948: E/AndroidRuntime(858): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
11-15 16:55:40.948: E/AndroidRuntime(858): at libcore.io.IoBridge.connect(IoBridge.java:112)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.net.Socket.connect(Socket.java:842)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-15 16:55:40.948: E/AndroidRuntime(858): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.example.androidhive.library.JSONParser.getJSONFromUrl(JSONParser.java:47)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.example.androidhive.library.UserFunctions.loginUser(UserFunctions.java:32)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.example.androidhive.LoginActivity$1.onClick(LoginActivity.java:61)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.view.View.performClick(View.java:4240)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.view.View$PerformClick.run(View.java:17721)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.os.Handler.handleCallback(Handler.java:730)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.os.Handler.dispatchMessage(Handler.java:92)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.os.Looper.loop(Looper.java:137)
11-15 16:55:40.948: E/AndroidRuntime(858): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.lang.reflect.Method.invokeNative(Native Method)
11-15 16:55:40.948: E/AndroidRuntime(858): at java.lang.reflect.Method.invoke(Method.java:525)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-15 16:55:40.948: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-15 16:55:40.948: E/AndroidRuntime(858): at dalvik.system.NativeStart.main(Native Method)
This exception is thrown when application tries to access network in main thread. This is forbidden as accessing resources over network may take indefinite amount of time and your main thread will be blocked untill network operation finishes, thus making your app frozen to the user.
Instead in your onClick() method you should start a new AsyncTask which will do the networking. After the task finishes proceed with updating the ui (changing activity etc.).

How to pass get text from userinput (edittext) and put into a textview in another activity?

I would like to take user input entered in the EditTextField(in the EnterNewFile class) and put it into the TextField (in the NoteEdit class). Please help! Thanks! FYI- I use XML files for the layouts of these two classes.
***********EnterNewFile.class*********
package com.example.note;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class EnterNewFile extends Activity {
public EditText mText;
public Button mButton;
public final static String EXTRA_MESSAGE = "com.example.note.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.new_file_start);
mText = (EditText)findViewById(R.id.file_name_edittext);
mButton = (Button)findViewById(R.id.next_button);
}
public void nextButton(View view)
{
/** Called when the user clicks the Next button */
Log.d("EditText", mText.getText().toString());
mText.getText().toString();
Intent intent = new Intent(this, NoteEdit.class);
EditText editText = (EditText) findViewById(R.id.file_name_edittext);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
//
}
}
******************************************
********NoteEdit.class************
package com.example.note;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class NoteEdit extends Activity{
public static int numTitle = 1;
public static String curDate = "";
public static String curText = "";
private TextView mTitleText;
private EditText mBodyText;
private TextView mDateText;
private Long mRowId;
private Cursor note;
private NotesDbAdapter mDbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
setContentView(R.layout.note_edit_add);
setTitle(R.string.app_name);
mTitleText = (TextView) findViewById(R.id.title);
mBodyText = (EditText) findViewById(R.id.body);
mDateText = (TextView) findViewById(R.id.notelist_date);
long msTime = System.currentTimeMillis();
Date curDateTime = new Date(msTime);
SimpleDateFormat formatter = new SimpleDateFormat("M'/'d'/'y");
curDate = formatter.format(curDateTime);
mDateText.setText(""+curDate);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(EnterNewFile.EXTRA_MESSAGE);
// Create the text view
// TextView textView = new TextView(this);
mTitleText.setText(message);
// Set the text view as the activity layout
// setContentView(textView);
// mTitleText.setText(dana);
mRowId = (savedInstanceState == null) ? null :
(Long) savedInstanceState.getSerializable(NotesDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID)
: null;
}
populateFields();
}
public void addFiles(View view)
{
/*Intent addFilesTarget = new Intent(this, Welcome.class);
startActivity(addFilesTarget);*/
}
public static class LineEditText extends EditText{
// we need this constructor for LayoutInflater
public LineEditText(Context context, AttributeSet attrs) {
super(context, attrs);
mRect = new Rect();
mPaint = new Paint();
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setColor(Color.BLUE);
}
private Rect mRect;
private Paint mPaint;
#Override
protected void onDraw(Canvas canvas) {
int height = getHeight();
int line_height = getLineHeight();
int count = height / line_height;
if (getLineCount() > count)
count = getLineCount();
Rect r = mRect;
Paint paint = mPaint;
int baseline = getLineBounds(0, r);
for (int i = 0; i < count; i++) {
canvas.drawLine(r.left, baseline + 1, r.right, baseline + 1, paint);
baseline += getLineHeight();
super.onDraw(canvas);
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveState();
outState.putSerializable(NotesDbAdapter.KEY_ROWID, mRowId);
}
#Override
protected void onPause() {
super.onPause();
saveState();
}
#Override
protected void onResume() {
super.onResume();
populateFields();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.noteedit_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_about:
/* Here is the intro about myself */
AlertDialog.Builder dialog = new AlertDialog.Builder(NoteEdit.this);
dialog.setTitle("About");
dialog.setMessage("Hello! I'm Dana, creator of this application. This is for documenting research."
+"\n melaninabeauty#gmail.com");
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
dialog.show();
return true;
case R.id.menu_delete:
if(note != null){
note.close();
note = null;
}
if(mRowId != null){
mDbHelper.deleteNote(mRowId);
}
finish();
return true;
case R.id.menu_save:
saveState();
finish();
default:
return super.onOptionsItemSelected(item);
}
}
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
if(mRowId == null){
mDbHelper.createNote(title, body, curDate);
}else{
mDbHelper.updateNote(mRowId, title, body, curDate);
}
}
private void populateFields() {
if (mRowId != null) {
note = mDbHelper.fetchNote(mRowId);
startManagingCursor(note);
mTitleText.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
mBodyText.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
curText = note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY));
}
}
}
***********************************
****AndroidManifest.xml****
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.note"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.note.Welcome"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.note.NoteList">
</activity>
<activity
android:name="com.example.note.NoteEdit">
</activity>
<activity
android:name="com.example.note.Export">
</activity>
<activity
android:name="com.example.note.NoteEditAdd">
</activity>
<activity
android:name="com.example.note.EnterNewFile">
</activity>
</application>
</manifest>
<!--
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.note"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity android:name="com.example.note.Welcome">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.note.NoteList"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.example.note.NoteEdit"
android:label="#string/edit_note"
android:parentActivityName="com.example.note.Welcome" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.note.Welcome" />
</activity>
</application>
</manifest>
-->
<!--
activity 2 android:name= com.example.note.NoteEdit
android:label=#string/app_name
android:windowSoftInputMode="djustUnspecified/>
-->
*****************************
> *****LogCat of crash**** Crash occurs after nextButton is clicked****(I inputted the text "nouy", clicked nextButton, then application crashes.********************
LogCat of crash** Crash occurs after nextButton is clicked*(I inputted the text "nouy", clicked nextButton, then application crashees.**
08-02 20:48:36.703: D/EditText(3575): nouy
08-02 20:48:36.793: I/Choreographer(3575): Skipped 68 frames! The application may be doing too much work on its main thread.
08-02 20:48:37.143: D/dalvikvm(3575): GC_CONCURRENT freed 1331K, 34% free 2956K/4428K, paused 4ms+59ms, total 137ms
08-02 20:48:37.353: D/AndroidRuntime(3575): Shutting down VM
08-02 20:48:37.394: W/dalvikvm(3575): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
08-02 20:48:37.443: E/AndroidRuntime(3575): FATAL EXCEPTION: main
08-02 20:48:37.443: E/AndroidRuntime(3575): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.note/com.example.note.NoteEdit}: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.os.Handler.dispatchMessage(Handler.java:99)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.os.Looper.loop(Looper.java:137)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.ActivityThread.main(ActivityThread.java:5041)
08-02 20:48:37.443: E/AndroidRuntime(3575): at java.lang.reflect.Method.invokeNative(Native Method)
08-02 20:48:37.443: E/AndroidRuntime(3575): at java.lang.reflect.Method.invoke(Method.java:511)
08-02 20:48:37.443: E/AndroidRuntime(3575): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
08-02 20:48:37.443: E/AndroidRuntime(3575): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
08-02 20:48:37.443: E/AndroidRuntime(3575): at dalvik.system.NativeStart.main(Native Method)
08-02 20:48:37.443: E/AndroidRuntime(3575): Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:424)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:50)
08-02 20:48:37.443: E/AndroidRuntime(3575): at com.example.note.NoteEdit.populateFields(NoteEdit.java:231)
08-02 20:48:37.443: E/AndroidRuntime(3575): at com.example.note.NoteEdit.onCreate(NoteEdit.java:99)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.Activity.performCreate(Activity.java:5104)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-02 20:48:37.443: E/AndroidRuntime(3575): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
08-02 20:48:37.443: E/AndroidRuntime(3575): ... 11 more
08-02 20:48:40.073: E/Trace(3598): error opening trace file: No such file or directory
(2)
Take the input from Edittext send it through the Intent to your destination activity and then set it in the TextView there.
I think you seem to already be doing that in your code:
The issue might be the you've not defined in your XML that nextButton function should be call on click ( inside android:onClick: inside your Button).
What you can also do is, in your onCreate funcion set up a listener which listens to the button click and call the intent from within it.
final EditText editText = (EditText) findViewById(R.id.file_name_edittext);
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/** Called when the user clicks the Next button */
Log.d("EditText", mText.getText().toString());
Intent intent = new Intent(EnterNewFile.this, NoteEdit.class);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
});
//here you are taking value from EditText and send it to other activity:
Instead of
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(EnterNewFile.EXTRA_MESSAGE);
use following in onCreate() of your other NoteEdit activity:
Intent intent = getIntent();
if((intent.getExtras()!=null) && !intent.getExtras().isEmpty()){
String message = intent.getExtras().getString(EnterNewFile.EXTRA_MESSAGE);
}
this code is working:-
scrollview=(ScrollView)findViewById(R.id.scrollview1);
tb2.setTextSize(30);
tb2.setMovementMethod(new ScrollingMovementMethod());
scrollview.post(new Runnable() {
public void run() {
scrollview.fullScroll(View.FOCUS_DOWN);
}
});
chat1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
{
textsaring1=edt1.getText().toString();
tb2.setText(tb2.getText()+" "+textsaring1);
edt1.setText("");
}
}
});

Android: startActivityForResult crashes during starting new activity

I am new Android coder and I'm fighting with function startActivityForResult. When I click Button that starts this method I can't go inside another activity because it crashes:
So there is MainActivity.java class. Here in public void setRegisterOnClick(View v) I want to use startActivityForResult twice, sending other intents to the same activity. Intents contain int number which is delivered to Users.class and used to declare giveResponse. But each time I click button launching startActivityForResult my app crashes.
package com.example.login;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private static final int USERS_REQUEST_CODE=1;
private static String sActualLogin = "admin";
private static String sActualPassword = "qwerty";
private static String sContainer = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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;
}
public void setLoginOnClick(View v)
{
EditText etLogin = (EditText) findViewById(R.id.tfLogin);
EditText etPassword = (EditText) findViewById(R.id.tfPassword);
String sLogin = etLogin.getText().toString();
String sPassword = etPassword.getText().toString();
if (sLogin.equals(sActualLogin) && sPassword.equals(sActualPassword))
{
Intent intent = new Intent (this, Inside.class);
startActivity(intent);
}
else
{
Toast.makeText(this, "Invalid username or password.", Toast.LENGTH_LONG).show();
}
}
public void setRegisterOnClick(View v)
{
Intent intentLOGIN = new Intent(this, Users.class);
intentLOGIN.putExtra("Type",1);
startActivityForResult(intentLOGIN, USERS_REQUEST_CODE);
sActualLogin=sContainer;
Intent intentPASSWORD= new Intent(this, Users.class);
intentPASSWORD.putExtra("Type",2);
startActivityForResult(intentPASSWORD, USERS_REQUEST_CODE);
sActualPassword=sContainer;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
sContainer = data.getStringExtra(Users.RESPONSE);
}
}
Users.class
package com.example.login;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class Users extends Activity {
public static final String RESPONSE = "Response";
EditText etNewLogin = (EditText) findViewById(R.id.etChangeLogin);
EditText etNewPassword = (EditText) findViewById(R.id.etChangePassword);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.users);
}
public void giveResponse(View v)
{
Intent intent = getIntent();
int iOperation = intent.getIntExtra("Type", 0);
if (iOperation == 1){
String sNewLogin = etNewLogin.getText().toString();
Intent resultIntent1 = new Intent();
resultIntent1.putExtra(RESPONSE, sNewLogin);
setResult(RESULT_OK, resultIntent1);
finish();
}
if (iOperation == 2){
String sNewPassword = etNewPassword.getText().toString();
Intent resultIntent2 = new Intent();
resultIntent2.putExtra(RESPONSE, sNewPassword);
setResult(RESULT_OK, resultIntent2);
finish();
}
}
}
Fragment of manifest:
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.login.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.login.Users"></activity>
<activity android:name="com.example.login.Inside"></activity>
</application>
Errors:
05-12 20:22:10.350: W/dalvikvm(6349): threadid=1: thread exiting with uncaught exception (group=0x40a191f8)
05-12 20:22:10.360: E/AndroidRuntime(6349): FATAL EXCEPTION: main
05-12 20:22:10.360: E/AndroidRuntime(6349): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.login/com.example.login.Users}: java.lang.NullPointerException
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1880)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.ActivityThread.access$600(ActivityThread.java:123)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.os.Handler.dispatchMessage(Handler.java:99)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.os.Looper.loop(Looper.java:137)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.ActivityThread.main(ActivityThread.java:4429)
05-12 20:22:10.360: E/AndroidRuntime(6349): at java.lang.reflect.Method.invokeNative(Native Method)
05-12 20:22:10.360: E/AndroidRuntime(6349): at java.lang.reflect.Method.invoke(Method.java:511)
05-12 20:22:10.360: E/AndroidRuntime(6349): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
05-12 20:22:10.360: E/AndroidRuntime(6349): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
05-12 20:22:10.360: E/AndroidRuntime(6349): at dalvik.system.NativeStart.main(Native Method)
05-12 20:22:10.360: E/AndroidRuntime(6349): Caused by: java.lang.NullPointerException
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.Activity.findViewById(Activity.java:1794)
05-12 20:22:10.360: E/AndroidRuntime(6349): at com.example.login.Users.<init>(Users.java:13)
05-12 20:22:10.360: E/AndroidRuntime(6349): at java.lang.Class.newInstanceImpl(Native Method)
05-12 20:22:10.360: E/AndroidRuntime(6349): at java.lang.Class.newInstance(Class.java:1319)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.Instrumentation.newActivity(Instrumentation.java:1023)
05-12 20:22:10.360: E/AndroidRuntime(6349): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1871)
05-12 20:22:10.360: E/AndroidRuntime(6349): ... 11 more
Well I wrote a lot for such trivial problem (I guess :P) but as I am unexperienced it takes hours to fights with it and I stil don't get it. Please guide/help me.
you must set the layout using setContentView before accessing the child widget using findViewByID
for example
private EditText etNewLogin;
private EditText etNewPassword;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.users);
tNewLogin = (EditText) findViewById(R.id.etChangeLogin);
tNewPassword = (EditText) findViewById(R.id.etChangePassword);
}
Also make sure that you are accesing the view using correct id
EditText etNewLogin;
EditText etNewPassword;;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.users);
etNewLogin = (EditText) findViewById(R.id.etChangeLogin);
etNewPassword = (EditText) findViewById(R.id.etChangePassword);
}
You need to find the id after setting the content to the activity.
Also in setLoginOnClick of MainActivity
Intent intent = new Intent (MainActivity.this, Inside.class);// use activity context
startActivity(intent);
Same for
Toast.makeText(MainActivit.this, "Invalid username or password.", Toast.LENGTH_LONG).show();
Intent intentLOGIN = new Intent(MainActivity.this, Users.class);// use activity context
intentLOGIN.putExtra("Type",1);
startActivityForResult(intentLOGIN, USERS_REQUEST_CODE);
sActualLogin=sContainer;
Intent intentPASSWORD= new Intent(MainActivity.this, Users.class);// use activity context
intentPASSWORD.putExtra("Type",2);
startActivityForResult(intentPASSWORD, USERS_REQUEST_CODE);
sActualPassword=sContainer;
Often this happens when you haven't declared an activity correctly in your AndroidManifest file, make sure the directory info is correct so your app can find the activity you are trying to get to!

Android radio streaming app crashes when you press pause or stop at the moment you haven't clicked play

When i start my app and press stop or pause the android app will crash. It works fine if you press play first and then stop or pause. I searched on google and stackoverflow but i couldn't find much about it. I think the problem is because of a NullPointerException but since i'm new too java it doesn't tell me much about the problem
The code:
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class myMain extends Activity implements
MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener, OnClickListener {
private String TAG = getClass().getSimpleName();
private MediaPlayer mp= null;
private Button play;
private Button pause;
private Button stop;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
play = (Button) findViewById(R.id.play);
pause = (Button) findViewById(R.id.pause);
stop = (Button) findViewById(R.id.stop);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
play();
}
});
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
stop();
}
});
}
private void play() {
Uri myUri = Uri.parse("url");
try {
if (mp == null) {
this.mp = new MediaPlayer();
} else {
mp.stop();
mp.reset();
}
mp.setDataSource(this, myUri); // Go to Initialized state
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnBufferingUpdateListener(this);
mp.setOnErrorListener(this);
mp.prepareAsync();
Log.d(TAG, "LoadClip Done");
} catch (Throwable t) {
Log.d(TAG, t.toString());
}
}
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "Stream is prepared");
mp.start();
}
private void pause() {
mp.pause();
}
private void stop() {
mp.stop();
}
#Override
public void onDestroy() {
super.onDestroy();
stop();
}
public void onCompletion(MediaPlayer mp) {
stop();
}
public boolean onError(MediaPlayer mp, int what, int extra) {
StringBuilder sb = new StringBuilder();
sb.append("Media Player Error: ");
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
}
sb.append(" (" + what + ") ");
sb.append(extra);
Log.e(TAG, sb.toString());
return true;
}
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.d(TAG, "PlayerService onBufferingUpdate : " + percent + "%");
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
The errors:
02-11 20:45:43.837: D/AndroidRuntime(338): Shutting down VM
02-11 20:45:43.837: W/dalvikvm(338): threadid=1: thread exiting with uncaught exception (group=0x40015560)
02-11 20:45:43.857: E/AndroidRuntime(338): FATAL EXCEPTION: main
02-11 20:45:43.857: E/AndroidRuntime(338): java.lang.NullPointerException
02-11 20:45:43.857: E/AndroidRuntime(338): at wadio.media.internetradio.myMain.stop(myMain.java:95)
02-11 20:45:43.857: E/AndroidRuntime(338): at wadio.media.internetradio.myMain.access$2(myMain.java:94)
02-11 20:45:43.857: E/AndroidRuntime(338): at wadio.media.internetradio.myMain$3.onClick(myMain.java:55)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.view.View.performClick(View.java:2485)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.view.View$PerformClick.run(View.java:9080)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.os.Handler.handleCallback(Handler.java:587)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.os.Handler.dispatchMessage(Handler.java:92)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.os.Looper.loop(Looper.java:123)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-11 20:45:43.857: E/AndroidRuntime(338): at java.lang.reflect.Method.invokeNative(Native Method)
02-11 20:45:43.857: E/AndroidRuntime(338): at java.lang.reflect.Method.invoke(Method.java:507)
02-11 20:45:43.857: E/AndroidRuntime(338): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-11 20:45:43.857: E/AndroidRuntime(338): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-11 20:45:43.857: E/AndroidRuntime(338): at dalvik.system.NativeStart.main(Native Method)
In your stop() method you access the mp variable. However, the mp variable is null until you press play (and the play() method is called). So when you try to access the null variable a NullPointerException is thrown.
A very simple way to stop the NullPointerException is to do something like this:
private void pause() {
if(mp!=null) mp.pause();
}
private void stop() {
if(mp!=null) mp.stop();
}
Of course this solution doesn't account for cases where pause or stop is called twice. Take a look at the MediaPlayer documentation for more info on state management.

Categories