I have 2 activity screens. The 1st one has 2 buttons.
Button1 processes the data based from the user inputs while Button2 leads the user to the next activity screen based from the result of the process.
Whenever I click Button1, nothing happens, and
when i click Button2, the app stops working and gives the "Unfortunately..." message. At first, everything is going well but then I added a few codes then the app won't run.
MainActivity
public class MainActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//for the header
View title = getWindow().findViewById(android.R.id.title);
if (title != null)
{
ViewParent titleBar = title.getParent();
if (titleBar != null && (titleBar instanceof View))
{
View parentView = (View)titleBar;
parentView.setBackgroundColor(Color.RED);
}
}
//for button2
Button next = (Button) findViewById(R.id.DGButton);
next.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(view.getContext(), Activity2.class);
startActivityForResult(myIntent, 0);
}
});
}
public void calculateClickHandler(View view)
{
//handle the click of button1
if (view.getId() == R.id.CalculateButton)
{
//some codes
//the next activity screen uses the calculated value for some outputs
Intent intent1 = new Intent(MainActivity.this, Activity2.class);
Bundle b = new Bundle();
b.putDouble("key", bmiValue);
intent1.putExtras(b);
startActivityForResult(intent1,0);
}
}
Activity2:
public class Activity2 extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Button next = (Button) findViewById(R.id.BackToBMI);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent();
setResult(RESULT_OK, intent);
finish();
}
});
//some codes
Bundle b = getIntent().getExtras(); //the nullpointerexception is here
double bmival = b.getDouble("key");
}
}
Logcat:
12-27 05:15:03.263: E/AndroidRuntime(1091): FATAL EXCEPTION: main
12-27 05:15:03.263: E/AndroidRuntime(1091): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bmicaldg/com.example.bmicaldg.Activity2}: java.lang.NullPointerException
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.os.Handler.dispatchMessage(Handler.java:99)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.os.Looper.loop(Looper.java:137)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.ActivityThread.main(ActivityThread.java:5039)
12-27 05:15:03.263: E/AndroidRuntime(1091): at java.lang.reflect.Method.invokeNative(Native Method)
12-27 05:15:03.263: E/AndroidRuntime(1091): at java.lang.reflect.Method.invoke(Method.java:511)
12-27 05:15:03.263: E/AndroidRuntime(1091): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-27 05:15:03.263: E/AndroidRuntime(1091): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-27 05:15:03.263: E/AndroidRuntime(1091): at dalvik.system.NativeStart.main(Native Method)
12-27 05:15:03.263: E/AndroidRuntime(1091): Caused by: java.lang.NullPointerException
12-27 05:15:03.263: E/AndroidRuntime(1091): at com.example.bmicaldg.Activity2.onCreate(Activity2.java:33)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.Activity.performCreate(Activity.java:5104)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
12-27 05:15:03.263: E/AndroidRuntime(1091): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
12-27 05:15:03.263: E/AndroidRuntime(1091): ... 11 more
And also this is the XML file for the MainActivity:
Button1:
<Button
android:id="#+id/CalculateButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView4"
android:layout_alignParentRight="true"
android:layout_marginBottom="14dp"
android:background="#FF0000"
android:minHeight="30dip"
android:minWidth="65dip"
android:onClick="calculateClickHandler"
android:text="#string/CalculateButton"
android:textColor="#FFFFFF"
android:textSize="14sp" />
Button2:
<Button
android:id="#+id/DGButton"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#FF0000"
android:minHeight="30dip"
android:onClick="calculateClickHandler"
android:text="#string/DGButton"
android:textColor="#FFFFFF" />
I'm a beginner in Android Mobile programming so any help would be appreciated.
This error is occurred because you are not passing double value in intent on click event of next button.
Write below code
Intent intent1 = new Intent(MainActivity.this, Activity2.class);
intent1.putExtra("key", bmiValue);
startActivity(intent1);
instead of below code on click event of next button and intent code of calculateClickHandler() method.
Intent myIntent = new Intent(view.getContext(), Activity2.class);
startActivityForResult(myIntent, 0);
it will solve your problem.
try replacing following code:
//for button2
Button next = (Button) findViewById(R.id.DGButton);
next.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(view.getContext(), Activity2.class);
startActivityForResult(myIntent, 0);
}
});
with this:
//for button2
Button next = (Button) findViewById(R.id.DGButton);
next.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(MainActivity.this, Activity2.class);
startActivityForResult(myIntent, 0);
}
});
EDIT1: updated after logcat logs..
in the last line of the method double bmival = b.getDouble("key"); you are trying to read value from the bundle. As per the following javadoc for the method getExtras():
it returns the map of all extras previously added with putExtra(), or
null if none have been added.
Now since you are not setting any value in the MainActivity by using putExtra(), you are getting null in the response to the call to getExtras(). So you need to call putExtra() in the MainActivity to pass some value to Activity2 like following code:
//for button2
Button next = (Button) findViewById(R.id.DGButton);
next.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(view.getContext(), Activity2.class);
//Assuming bmival is a class variable that has the value that you want to pass on to Activity2
myIntent.putExtra("key",bmival);
startActivityForResult(myIntent, 0);
}
});
Also please put a null check before reading value form the bundle like in the following code:
if(b!=null){
double bmival = b.getDouble("key");
}
There might be few errors,
First and the most possible case might be that you have not defined your second Activity in your manifest file. So first check that whether you have defined all of your activities in manifest file.
The following statement is completely wrong.
Intent myIntent = new Intent(view.getContext(), Activity2.class);
Here you are using View of Buttin's onClickListener, but instead you should be using either the Activity Context, like MyActivity.this or the Application's Context, like this getApplicationContext().
Try to use
startActivity(myIntent);
instead of
startActivityForResult(myIntent, 0);
If at all your problem is not solved, the last not so possible case might be,
try adding flags to the intent, like this
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
You are not setting any values in the Intent Extras, Although it would give you an error in the next Activity,
myIntent.putExtra("key", bmiValue);
I think you looking for this, try this
//for button2
Button next = (Button) findViewById(R.id.DGButton);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(MainActivity.this, Activity2.class);
Bundle b = new Bundle();
b.putDouble("key", bmiValue);
intent1.putExtras(b);
startActivityForResult(myIntent, 0);
}
});
Its better to Use startActivity() instead of startActivityForResult(intent1,0)
and also in your receiving side check whether the you are getting extras are not
So Try like this
Bundle extras = getIntent().getExtras();
if(extras != null)
{
double bmival = extras.getDouble("key");
}
Related
I was using an integer for the money factor in this little test app but I realized that long was more appropriate and I changed the code so that money is a long instead of an int and I changed SharedPreferences appropriately as well, however it does not work wheras it did when I used int. Thank you for the help!
public class Home extends AppCompatActivity {
SharedPreferences pref;
SharedPreferences.Editor editor;
Intent intent;
TextView home_money_view;
long money; // this is the variable that is causing problems
int initial;
final long TEST = (long)-1;
int gold_pieces;
int gold_price = 50;
TimerTask timerTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
home_money_view = (TextView) findViewById(R.id.home_money_view)
pref = getApplicationContext().getSharedPreferences("MY_PREFS", MODE_PRIVATE);
editor = pref.edit();
money = pref.getLong("temp_money",Long.MIN_VALUE); // get value
if (money==Long.MIN_VALUE){
money=0;
}
gold_pieces = pref.getInt("temp_gold",-1);
if (gold_pieces==-1){
gold_pieces=0;
}
initial = pref.getInt("initial",0);
money+=initial;
editor.putInt("initial",0);
editor.commit();
home_money_view = (TextView) findViewById(R.id.home_money_view);
home_money_view.setText(money+"");
editor.commit();
}
public void backToSplash(View view){
intent = new Intent(Home.this,BusinessSelector.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
public void goToSecondView(View view){
long temp_money = money;
editor.putLong("temp_money",temp_money); // set value
int temp_gold = gold_pieces;
editor.putInt("temp_gold",temp_gold);
editor.commit();
intent = new Intent(Home.this,SecondView.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
public void goToOtherView(View view) {
long temp_money = money;
editor.putLong("temp_money",temp_money); // set value
int temp_gold = gold_pieces;
editor.putInt("temp_gold", temp_gold);
editor.commit();
intent = new Intent(Home.this, Next.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
Logcat:
04-13 19:01:03.675 12896-12896/com.exampleryancocuzzo.ryan.markettycoon E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exampleryancocuzzo.ryan.markettycoon/com.exampleryancocuzzo.ryan.markettycoon.Home}: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
at android.app.SharedPreferencesImpl.getLong(SharedPreferencesImpl.java:228)
at com.exampleryancocuzzo.ryan.markettycoon.Home.onCreate(Home.java:56)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
I have the following class SubMenuToolBar which I usually instantiate from an activity (MainActivity) that passes itself (this) in the constructor upon instantiation:
public class SubMenuToolBar extends Activity {
private android.support.v7.widget.Toolbar mToolbar;
private Activity mActivity;
RelativeLayout mLayout;
public SubToolbar(android.support.v7.widget.Toolbar toolbar, Activity activity) {
mActivity = activity;
mToolbar = toolbar;
mLayout = (RelativeLayout) mToolbar.findViewById(R.id.layout_toolbar);
mLayout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(mActivity, UserMessagesActivity.class);
startActivity(intent);
}
});
}
MainActivity.cs
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new SubMenuToolBar ((android.support.v7.widget.Toolbar) findViewById(R.id.sub_toolbar), this);
}
Everytime I click on the element registered with the click event handler (in the activity) I get the popular error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
11-20 08:31:33.422 23802-23802/com.xxx.apps.xxx E/AndroidRuntime: at android.app.Activity.startActivityForResult(Activity.java:3918)
11-20 08:31:33.422 23802-23802/com.xxx .apps.xxx E/AndroidRuntime: at android.app.Activity.startActivityForResult(Activity.java:3877)
11-20 08:31:33.422 23802-23802/com.xxx.apps.xxx E/AndroidRuntime: at android.app.Activity.startActivity(Activity.java:4200)
11-20 08:31:33.422 23802-23802/com.xxx.apps.xxx E/AndroidRuntime: at android.app.Activity.startActivity(Activity.java:4168)
11-20 08:31:33.422 23802-23802/com.xxx.apps.xxx E/AndroidRuntime: at com.xxx.apps.xxx.SubMenuToolBar$1.onClick(SubToolbar.java:28)
I have tried using the Activity in the Intent, the Context of the activity, getApplicationContext, and getBaseContext. All throws the same error on line:
Intent intent = new Intent(mActivity, MessagesActivity.class);
I have checked SO and various web resource where most of them point to the activity need to be passed to the class so it's Context is used in the Intent, I have done that as you can see above and made sure all details of the calling Activity is passed and used, the problem is still there.
Any idea what I'm doing wrong here?
try replace this:
Intent intent = new Intent(mActivity, UserMessagesActivity.class);
startActivity(intent);
to this:
Intent intent = new Intent(mActivity, UserMessagesActivity.class);
mActivity.startActivity(intent);
You are a little confused. Activity must not be instantiated with new. You have to start it using Intent. There is two activities but I think you only need one.
public class SubMenuToolBar extends Activity {
RelativeLayout mLayout;
#Override
protected void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.your_activity_layout);
android.support.v7.widget.Toolbar mToolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.sub_toolbar);
mLayout = (RelativeLayout)mToolbar.findViewById(R.id.layout_toolbar);
mLayout.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(mActivity, UserMessagesActivity.class);
startActivity(intent);
});
}
And use SubMenuToolBar as your main activity.
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText txtUserName = (EditText)findViewById(R.id.editText1);
final EditText txtPassword = (EditText)findViewById(R.id.editText2);
Button btnLogin = (Button)findViewById(R.id.button1);
btnLogin.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
String username = txtUserName.getText().toString();
String password = txtPassword.getText().toString();
String foo = new String("131031001");
String foo2 = new String("131031002");
String foo3 = new String("131031003");
String foo4 = new String("131031004");
String foo5 = new String("131031005");
try{
if(username.length() > 0 && password.length() >0) {
DBUserAdapter dbUser = new DBUserAdapter(MainActivity.this);
dbUser.open();
dbUser.AddUser();
if(dbUser.Login(username, password))
{
Toast.makeText(MainActivity.this,"Successfully Logged In", Toast.LENGTH_LONG).show();
if(username.equals(foo))
{
Intent nextActivity2 = new Intent(getApplicationContext(),SecondActivity.class);
nextActivity2.putExtra("Second",username);
startActivity(nextActivity2);
}
else if(username.equals(foo2)) {
Intent nextActivity3 = new Intent(getBaseContext(),ThirdActivity.class);
nextActivity3.putExtra("Third",username);
startActivity(nextActivity3);
}
else if(username.equals(foo3))
{
Intent nextActivity4 = new Intent(getBaseContext(),FourthActivity.class);
nextActivity4.putExtra("Fourth",username);
startActivity(nextActivity4);
}
else if(username.equals(foo4)) {
Intent nextActivity5 = new Intent(getBaseContext(),FifthActivity.class);
nextActivity5.putExtra("Fifth",username);
startActivity(nextActivity5);
}
else if(username.equals(foo5)) {
Intent nextActivity6 = new Intent(getBaseContext(),SixthActivity.class);
nextActivity6.putExtra("Sixth",username);
startActivity(nextActivity6);
}
else {
Toast.makeText(MainActivity.this,"Result does not exist! Try later!!", Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(MainActivity.this,"Invalid Username/Password", Toast.LENGTH_LONG).show();
}
dbUser.close();
}
}catch(Exception e) {
Toast.makeText(MainActivity.this,e.getMessage(), Toast.LENGTH_LONG).show();
}
}
});
Button btreg = (Button)findViewById(R.id.button2);
btreg.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Intent nextActivity = new Intent(getApplicationContext(),Register.class);
startActivity(nextActivity);
}
});
}
}
SecondActivity.java
public class SecondActivity extends Activity {
Intent intent = getIntent();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
}
}
All other activities are coded similar to the above.
Here is my logcat.
10-28 14:53:10.688: E/AndroidRuntime(1196): Process: com.skcetresults, PID: 1196
10-28 14:53:10.688: E/AndroidRuntime(1196): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.skcetresults/com.skcetresults.SecondActivity}: java.lang.NullPointerException
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2176)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.access$700(ActivityThread.java:135)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.os.Handler.dispatchMessage(Handler.java:102)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.os.Looper.loop(Looper.java:137)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.main(ActivityThread.java:4998)
10-28 14:53:10.688: E/AndroidRuntime(1196): at java.lang.reflect.Method.invokeNative(Native Method)
10-28 14:53:10.688: E/AndroidRuntime(1196): at java.lang.reflect.Method.invoke(Method.java:515)
10-28 14:53:10.688: E/AndroidRuntime(1196): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
10-28 14:53:10.688: E/AndroidRuntime(1196): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
10-28 14:53:10.688: E/AndroidRuntime(1196): at dalvik.system.NativeStart.main(Native Method)
10-28 14:53:10.688: E/AndroidRuntime(1196): Caused by: java.lang.NullPointerException
10-28 14:53:10.688: E/AndroidRuntime(1196): at com.skcetresults.SecondActivity.onCreate(SecondActivity.java:15)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.Activity.performCreate(Activity.java:5243)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-28 14:53:10.688: E/AndroidRuntime(1196): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2140)
10-28 14:53:10.688: E/AndroidRuntime(1196): ... 11 more
With just two intents the code worked fine, but when I'm comparing the value with strings, the app crashes, I don't know where the bug is.
Instead of getBaseContext() and getApplicationContext(), use MainActivity.this as context, will work everywhere.
You should put it like this
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
Intent i = getIntent();
}
}
If the extra data are strings you can get it like this:
String nameString = i.getStringExtra("nameExtra");
You can't use getIntent() before onCreate(), there's simply no Intent available at that point.
In your code, I suspect that you are trying to get StringExtras from Intent, But as intent is null, it is throwing NullPointerException.
In your Second Activity you can use getIntent() in onCreate() method.
public class SecondActivity extends Activity {
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second_activity);
intent = getIntent();
String userName = intent.getStringExtra("Second");
...
}
}
Use little pieces of code checking, to ensure your intent behaves properly. For example, you could surround your getIntent code with an if statement. For which proper method to call, you have to wander around a bit, as this depends on what you want your app to do. Fortunately, Eclipse delivers you all the related documentation, when you write down some piece of Android resources, e.g. Intent.
In my listview there are to feilds,ward number and the date.i want to get these data to new activity when i'am clicking a listview.but in this there is a runtime error and i have no idea to how to fix it.
this is my dashboardActivity.java file,
public class DashboardActivity extends ListActivity implements FetchDataListener{
UserFunctions userFunctions;
Button btnLogout;
TextView resultView;
private ProgressDialog dialog;
//private String email;
#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);
initView();
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
TextView txtviewWard= (TextView) view.findViewById(R.id.ward_number);
String ward = txtviewWard.getText().toString();
TextView txtviewDate= (TextView) view.findViewById(R.id.date_time);
String dateTime = txtviewDate.getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
i.putExtra("ward", ward);
i.putExtra("dateTime", dateTime);
startActivity(i);
}
});
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();
}
}
private void initView() {
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
Intent intent = getIntent();
String email = intent.getStringExtra(LoginActivity.EMAIL);
String url = "http://pubbapp.comze.com/pubapp1.php?email=" + email;
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
public void onFetchComplete(List<Application> data) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// create new adapter
ApplicationAdapter adapter = new ApplicationAdapter(this, data);
// set the adapter to list
setListAdapter(adapter);
}
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if(dialog != null) dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
}
this is my SingleListItem.java file,
public class SingleListItem extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_list_item_view);
TextView txtWard = (TextView) findViewById(R.id.ward_number);
TextView txtDate = (TextView) findViewById(R.id.date_time);
Intent i = getIntent();
// getting attached intent data
String wardNumber = i.getStringExtra("ward");
String dateTime = i.getStringExtra("dateTime");
// displaying selected product name
txtWard.setText(wardNumber);
txtDate.setText(dateTime);
}
this is my xml file,
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/ward_number"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:text="wardNumber"
android:textColor="#ffffff"
android:textSize="25dip"
android:textStyle="bold" />
<TextView
android:id="#+id/date_time"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Date"
android:padding="10dip"
android:textColor="#ffffff"
android:textSize="20dip"
android:textStyle="bold" />
</LinearLayout>
and this is the error in the LogCat,
12-02 19:10:01.100: E/AndroidRuntime(22705): FATAL EXCEPTION: main
12-02 19:10:01.100: E/AndroidRuntime(22705): java.lang.NullPointerException
12-02 19:10:01.100: E/AndroidRuntime(22705): at com.example.androidhive.DashboardActivity$1.onItemClick(DashboardActivity.java:59)
12-02 19:10:01.100: E/AndroidRuntime(22705): at android.widget.AdapterView.performItemClick(AdapterView.java:284)
12-02 19:10:01.100: E/AndroidRuntime(22705): at android.widget.ListView.performItemClick(ListView.java:3745)
12-02 19:10:01.100: E/AndroidRuntime(22705): at android.widget.AbsListView$PerformClick.run(AbsListView.java:1980)
12-02 19:10:01.100: E/AndroidRuntime(22705): at android.os.Handler.handleCallback(Handler.java:587)
12-02 19:10:01.100: E/AndroidRuntime(22705): at android.os.Handler.dispatchMessage(Handler.java:92)
12-02 19:10:01.100: E/AndroidRuntime(22705): at android.os.Looper.loop(Looper.java:130)
12-02 19:10:01.100: E/AndroidRuntime(22705): at android.app.ActivityThread.main(ActivityThread.java:3691)
12-02 19:10:01.100: E/AndroidRuntime(22705): at java.lang.reflect.Method.invokeNative(Native Method)
12-02 19:10:01.100: E/AndroidRuntime(22705): at java.lang.reflect.Method.invoke(Method.java:507)
12-02 19:10:01.100: E/AndroidRuntime(22705): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
12-02 19:10:01.100: E/AndroidRuntime(22705): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
12-02 19:10:01.100: E/AndroidRuntime(22705): at dalvik.system.NativeStart.main(Native Method)
please help me to fix this error.
thank you.
In first activity, pass the data as a bundle using putExtras:
// sending data to new activity
Bundle b = new Bundle();
b.putString("ward", ward);
b.putString("dateTime", dateTime);
i.putExtras(b);
In second activity, retrieve the bundle and parse the data as follows:
Bundle b = getIntent().getExtras();
if (b != null)
{
String wardNumber = b.getString("ward");
String dateTime = b.getString("dateTime");
}
try this....
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//your code
}
});
get data like this in ur second activity:
Bundle b = savedInstanceState.getExtras();
if(b!=null)
{
String ward =b.getString("ward");
String dateTime =b.getString("datetime");
}
bundle is responsible to getexras(),so use this.it worked for me and my other friends.
I have a program which is as follows, Can anyone tell me what is the reason for getting an NPE.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
secondClass x = new secondClass();
x.sText("Test Spring");
}
}
public class secondClass extends MainActivity {
public void sText(String s) {
TextView text = (TextView) findViewById(R.id.text);
text.setText(s);
}
}
Mainfest
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
...
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:id="#+id/text"
/>
</RelativeLayout>
LogCat
08-16 01:31:11.320 15032-15032/? E/Trace: error opening trace file: No such file or directory (2)
08-16 01:31:11.420 836-987/? E/EmbeddedLogger: App crashed! Process: com.example.myapplication
08-16 01:31:11.420 836-987/? E/EmbeddedLogger: App crashed! Package: com.example.myapplication v1 (1.0)
08-16 01:31:11.420 836-987/? E/EmbeddedLogger: Application Label: My Application
08-16 01:31:11.420 15032-15032/? E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java)
at android.app.ActivityThread.access$600(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java)
at android.os.Handler.dispatchMessage(Handler.java)
at android.os.Looper.loop(Looper.java)
at android.app.ActivityThread.main(ActivityThread.java)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:110)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java)
at com.example.myapplication.secondClass.sText(secondClass.java:13)
at com.example.myapplication.MainActivity.onCreate(MainActivity.java:14)
at android.app.Activity.performCreate(Activity.java)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java)
To my understanding, this should instantiate and initialize a secondClass object then call its sText() method. The sText method should then store a reference in TextView. Next it calls the setText() method on TextView, which changes the text in the TextView to what was passed into sText().
The logcat says it throws a NullPointerException but I'm not entirely sure why. If this is a rookie mistake, it's because I am a rookie. Thank you.
You need to Override onCreate in your secondActivity and have setContentView(R.layout.mylayout). Then you can initialize your textview.
Also you need to start an Activity using intent
Intent intent = new Intent(MainActivtiy.this,SecondActivity.class);
startActivity(intent);
Remember to make an entry for the activity (SecondActivtiy) in manifest file
If you need to pass the string to second activity use intent.putExtra
Intent intent = new Intent(MainActivtiy.this,SecondActivity.class);
intent.putExtra("key",mystring);
startActivity(intent);
Then in secondActivity
TextView tv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mysecondlayout);
tv = (TextView) findViewByid(R.id.textView1);
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("key");
tv.setText(value);
//get the value based on the key
}
http://developer.android.com/reference/android/content/Intent.html#putExtra(java.lang.String, android.os.Bundle)
You can findViewById of the current view herarchy set to the activity.
Also you need to startActivity using intent rather doing this econdClass x = new secondClass()