This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I can not understand why my application does not open a new activity on a button click.I have a button in my layout file(id is showButton),I need to open another activity when I click on that button.But it does not work and my application will crash.therefore I added a try catch block and get the android monitor result as following.
activity_place_picker.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".PlacePickerActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView2"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Launch Places API Picker"
android:id="#+id/pickerButton"
android:layout_below="#+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add to Place Holder"
android:id="#+id/saveButton"
android:layout_below="#+id/pickerButton"
android:layout_centerHorizontal="true"
android:visibility="gone"
android:layout_marginTop="20dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Place Holder"
android:id="#+id/showButton"
android:layout_below="#+id/saveButton"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView3"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView3"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/poweredBy"
android:src="#drawable/powered_by_google_light"/>
This is Place picker class where I have included the onClick listner to the button to open a new activity.
PlacePickerActivity
public class PlacePickerActivity extends AppCompatActivity {
private static final int PLACE_PICKER_REQUEST = 1;
private TextView mName;
private TextView mAddress;
private TextView mAttributions;
private static final LatLngBounds BOUNDS_MOUNTAIN_VIEW = new LatLngBounds(
new LatLng(37.398160, -122.180831), new LatLng(37.430610, -121.972090));
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_picker);
mName = (TextView) findViewById(R.id.textView);
mAddress = (TextView) findViewById(R.id.textView2);
mAttributions = (TextView) findViewById(R.id.textView3);
Button showButton = (Button) findViewById(R.id.showButton);
Button pickerButton = (Button) findViewById(R.id.pickerButton);
pickerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
PlacePicker.IntentBuilder intentBuilder =
new PlacePicker.IntentBuilder();
intentBuilder.setLatLngBounds(BOUNDS_MOUNTAIN_VIEW);
Intent intent = intentBuilder.build(PlacePickerActivity.this);
startActivityForResult(intent, PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException
| GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
});
showButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
try {
Intent i = new Intent(ctx, PlacesActivity.class);
ctx.startActivity(i);
}catch (Exception e){
e.printStackTrace();
}
}
});
}
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent data) {
if (requestCode == PLACE_PICKER_REQUEST
&& resultCode == Activity.RESULT_OK) {
//Extracting place information from the API
final Place place = PlacePicker.getPlace(this, data);
final String place_Id = place.getId().toString();
final String place_Name = place.getName().toString();
final String place_Address = place.getAddress().toString();
final String place_PhoneNumber = place.getPhoneNumber().toString();
final String place_Website = place.getWebsiteUri().toString();
//Get rating as a float value and converting to string
final float rating = place.getRating();
final String place_Rating = String.valueOf(rating);
final String place_LatLng = place.getLatLng().toString();
final String function_Save = "save_Place";
final String function_Show = "show_Place";
String attributions = (String) place.getAttributions();
if (attributions == null) {
attributions = "";
}
mName.setText(place_Name);
mAddress.setText(place_Address);
mAttributions.setText(Html.fromHtml(attributions));
//Accessing the save button and show button in the view and making it visible after selecting a place
final View save = findViewById(R.id.saveButton);
save.setVisibility(View.VISIBLE);
//Passing the Extracted place details to the background worker class
save.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
BackgroundWorker backgroundWorker = new BackgroundWorker(PlacePickerActivity.this);
backgroundWorker.execute(function_Save,place_Id,place_Name,place_Address,place_PhoneNumber,place_Website,place_Rating,place_LatLng);
}
});
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
PlacesActivity.java
package com.truiton.placepicker;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class PlacesActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_places);
}
}
activity_places.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.truiton.placepicker.PlacesActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello world"
android:id="#+id/textView" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.truiton.placepicker">
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyBpIGvJfE8eKhoEFCMqV8NrFkWRjTAnNyQ" />
<activity
android:name=".PlacePickerActivity"
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=".PlacesActivity"></activity>
</application>
</manifest>
Android Monitor result when the button clicks
Android Monitor result
Edited : This is the crash log
Crash log
can anyone help me with this?
Write the class name PlacePickerActivity in the intent, your method should be
showButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
try {
Intent i = new Intent(PlacePickerActivity.this , PlacesActivity.class);
ctx.startActivity(i);
}catch (Exception e){
e.printStackTrace();
}
}
});
I found the answer for the question.
This
link helped me to find the answer for the problem. In PlacePickerActivity I have just declare Context ctx;and it does not contain any primitive value. But I have use the it as an argument to open a new activity which will give me a NullPointerException.So instead of
showButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent i = new Intent(ctx, PlacesActivity.class);
ctx.startActivity(i);
}
});
I used
showButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent i = new Intent(PlacePickerActivity.this, PlacesActivity.class);
PlacePickerActivity.this.startActivity(i);
}
});
And this fixed my problem.Thank you for every one.
Related
I am very new to coding, this being only my 2nd semester in community college and therefore I have a lot to learn.
In my Android Development course, I have been tasked to use the program I've created from the Android Development lesson here - https://developer.android.com/training/basics/firstapp/starting-activity#java - as the basis for a new program which instead has 2 textboxes and which displays the content the user inputs into those textboxes, onto the display screen, by clicking the 1 send button.
I am stuck.
I've been at this since last Tuesday when the challenge was issued and I've been Google searching, DuckDuckGo searching, searching through stackoverflow, searching through here - https://developer.android.com/docs/ - and I've tried many different approaches but I can't seem to find out how to accomplish this.
!!For the record: I'm not asking someone to code the program/app for me. I'm simply trying to understand how to get this 1 button to send 2 textbox contents to the display - I want to learn!!
//* activity_main.xml */
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/ColorActivity"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:ems="10"
android:gravity="center"
android:layout_toRightOf="#+id/Number"
android:hint="edit_name_message"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:layout_below="#+id/Name"
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:layout_centerHorizontal="true"
android:text="button_send"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/Number" />
<EditText
android:id="#+id/Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:ems="10"
android:gravity="center"
android:hint="edit_phone_message"
android:inputType="phone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/Name" />
</RelativeLayout>
//* DisplayMessge.java */
package com.example.testapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
import com.example.testapp.R;
public class DisplayMessage extends Activity {
private TextView name;
private TextView number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_activity);
name = findViewById(R.id.NameText);
number = findViewById(R.id.NumberText);
Intent getText = getIntent();
String TheName = getText.getStringExtra("Name");
String TheNumber = getText.getStringExtra("Number");
name.setText(TheName);
number.setText(TheNumber);
}
}
//* MainActivity.java */
package com.example.testapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.example.testapp.DisplayMessage;
import com.example.testapp.R;
public class MainActivity extends AppCompatActivity {
Button button;
private EditText name;
private EditText number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialization of the EditText and the Button
name = (EditText) findViewById(R.id.Name);
number = (EditText) findViewById(R.id.Number);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), DisplayMessage.class);
String mName = name.getText().toString();
String mNumber = number.getText().toString();
//Checking if the Entries are empty
if (mName != null && mNumber != null) {
intent.putExtra("Name", mName);
intent.putExtra("Number", mNumber);
startActivity(intent);
finish();
} else {
Toast.makeText(getApplicationContext(), "Text Entries Missing", Toast.LENGTH_SHORT).show();
}
}
});
}
}
//* AndroidManifest.xml */
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testapp">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".DisplayMessage">
<intent-filter>
<action android:name="android.intent.action.VIEW"></action>
</intent-filter>
</activity>
</application>
</manifest>
//* display_activity.xml */
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="match_parent">
<TextView
android:layout_gravity="center"
android:id="#+id/NameText"
android:layout_weight="1"
android:textSize="18sp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/NumberText"
android:layout_gravity="center"
android:textSize="18sp"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
You have to implement the onClick function and send the intent from there.
public class MainActivity extends AppCompatActivity {
Button button;
private EditText name;
private EditText number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialization of the EditText and the Button
name = (EditText) findViewById(R.id.Name);
number = (EditText) findViewById(R.id.Number);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), DisplayMessage.class);
String mName = name.getText().toString();
String mNumber = number.getText().toString();
//Checking if the Entries are empty
if(mName!=null&&mNumber!=null) {
intent.putExtra("Name", mName);
intent.putExtra("Number", mNumber);
startActivity(intent);
finish();
}else{
Toast.makeText(getApplicationContext(),"Text Entries Missing",Toast.LENGTH_SHORT).show();
}
}
});
and the Display Class:
public class DisplayMessage extends Activity {
private TextView name;
private TextView number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_activity);
name = findViewById(R.id.NameText);
number = findViewById(R.id.NumberText);
Intent getText = getIntent();
String TheName =getText.getStringExtra("Name");
String TheNumber = getText.getStringExtra("Number");
name.setText(TheName);
number.setText(TheNumber);
}
Also don't forget to add your displayActivity to the AndroidManifest.xml
<activity android:name=".DisplayMessage">
<intent-filter>
<action android:name="android.intent.action.VIEW"></action>
</intent-filter>
</activity>
Now you have to create a second user interface for the DisplayMessageActivity go to res/layout, right click on the layout folder and create a new layout named display_activity. This is my code for the display_activity.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="match_parent">
<TextView
android:layout_gravity="center"
android:id="#+id/NameText"
android:layout_weight="1"
android:textSize="18sp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/NumberText"
android:layout_gravity="center"
android:textSize="18sp"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Lastly this is the activity_main layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="#+id/ColorActivity"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="#+id/Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:ems="10"
android:gravity="center"
android:layout_toRightOf="#+id/Number"
android:hint="edit_name_message"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:layout_below="#+id/Name"
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:layout_centerHorizontal="true"
android:text="button_send"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/Number" />
<EditText
android:id="#+id/Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:ems="10"
android:gravity="center"
android:hint="edit_phone_message"
android:inputType="phone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/Name" />
</RelativeLayout>
Just reduce your two functions (snedNumber and sendName) to only one function. Inside this function you get the text of both textfields and put them into your intentextra. then simply start your new activity
Do it like this
public void sendInfo(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText name = (EditText) findViewById(R.id.Name);
String message = name.getText().toString();
EditText number = (EditText) findViewById(R.id.Number);
String message2 = number.getText().toString();
intent.putExtra("firstString", message);
intent.putExtra("secondString", message2);
startActivity(intent);
}
And in your DisplayMessageActivity class onCreate method get it like
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity);
Bundle extra = getIntent().getExtras();
if (extra != null){
String message = extra.getString("firstString");
String message2 = extra.getString("secondString");
}
}
I want from user to input his name in one EditText widget, then to input his weight in other EditText widget, and after that to proceed that data from one activity to another one.
Weight input should later be included in one formula, and name input should be settled in TextView widget with result of the formula.
But, when i start my app, at the end Android Studio shows me NullPointerException. I suppose that err is somewhere in data sharing between activities.
So, here is the code. If you can, pls help me :)
ActivityOne (name of activity is InformacijeM) XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_informacije_m"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.alkometar.InformacijeM"
android:background="#drawable/activitybackground">
<TextView
android:text="Ukucaj svoje ime"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="29dp"
android:textSize="25dp"
android:textColor="#android:color/black"
android:textStyle="bold"
android:id="#+id/UkucajIme" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#drawable/strelamanja"
android:id="#+id/strelica"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="28dp" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text=""
android:ems="10"
android:id="#+id/ImeInput"
android:layout_marginTop="12dp"
android:layout_below="#+id/UkucajIme"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:text=""
android:ems="10"
android:id="#+id/MasaInput"
android:layout_marginBottom="53dp"
android:layout_above="#+id/strelica"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
/>
<TextView
android:text="Ukucaj svoju masu u kg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/UkucajMasu"
android:textSize="25dp"
android:textColor="#android:color/black"
android:textStyle="bold"
android:layout_marginBottom="30dp"
android:layout_above="#+id/MasaInput"
android:layout_centerHorizontal="true" />
</RelativeLayout>
ActivityOne (InformacijeM) Java file:
package com.example.alkometar;
import android.content.Intent;
import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
public class InformacijeM extends AppCompatActivity {
EditText ImeTxt, MasaTxt ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_informacije_m);
// INICIRANJE VREDNOSTI
EditText ImeTxt = (EditText)findViewById(R.id.ImeInput);
final String str1 = ImeTxt.getText().toString();
EditText MasaTxt = (EditText)findViewById(R.id.MasaInput);
final String str2 = MasaTxt.getText().toString();
ImageButton btn = (ImageButton)findViewById(R.id.strelica);
// PREBACIVANJE AKTIVITIJA
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(InformacijeM.this, RezultatM.class);
intent1.putExtra("keyIme", str1);
intent1.putExtra("keyMasa", str2);
Intent intent = new Intent(InformacijeM.this, StanjeM.class);
startActivity(intent);
}
});
}}
ActivityTwo (Name of activity is RezultatM) XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_rezultat_m"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.alkometar.RezultatM"
android:background="#drawable/activitybackground">
<TextView
android:text=""
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="97dp"
android:id="#+id/rezultatTekst" />
<Button
android:text="Rezultat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:id="#+id/button" />
</RelativeLayout>
ActivityTwo (RezultatM) Java file:
package com.example.alkometar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class RezultatM extends AppCompatActivity {
TextView rezultat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rezultat_m);
rezultat = (TextView) findViewById(R.id.rezultatTekst);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Bundle extras = getIntent().getExtras();
{
String str1 = extras.getString("keyIme");
String str2 = extras.getString("keyMasa");
double masad = Double.valueOf(str2);
double nekibroj = 0.8;
double result = masad * nekibroj;
rezultat.setText(str1 + "Nivo alkohola u tvojoj krvi je:" + result);
}
};
});
}}
Strings.xml file:
<resources>
<string name="app_name">Alkometar</string>
<string name="ImeInput">ImeInput</string>
<string name="MasaInput">MasaInput</string>
</resources>
AndroidManifest XML file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alkometar">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Pol">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".InformacijeM" />
<activity android:name=".StanjeM" />
<activity android:name=".InformacijeZ" />
<activity android:name=".StanjeZ" />
<activity android:name=".PijemM" />
<activity android:name=".RezultatM"></activity>
</application>
</manifest>
And here is the exception in logCat:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.alkometar, PID: 30732
java.lang.NullPointerException
at com.example.alkometar.RezultatM$1.onClick(RezultatM.java:28)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18770)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5292)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Thank you very much once again! :)))
Change your Activity Two class to:
public class RezultatM extends AppCompatActivity {
TextView rezultat;
String str1,str2;
double masad;
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rezultat_m);
rezultat = (TextView) findViewById(R.id.rezultatTekst);
Button button = (Button) findViewById(R.id.button);
//Intent intent = getIntent();
//str1 = intent.getStringExtra("keyIme");
//str2 = intent.getStringExtra("keyMasa");
//getting values from shared preferences
SharedPreferences shared = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
str1=shared.getString("keyIme", "");
str2=shared.getString("keyMasa", "");
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
if(str2!=null){
masad = Double.parseDouble(str2);
}
double nekibroj = 0.8;
double result = masad * nekibroj;
rezultat.setText(str1 + "Nivo alkohola u tvojoj krvi je:" + result);
};
});
}}
Also in your Activity one you are starting wrong intent
Intent intent1 = new Intent(InformacijeM.this, RezultatM.class);
intent1.putExtra("keyIme", str1);
intent1.putExtra("keyMasa", str2);
Intent intent = new Intent(InformacijeM.this, StanjeM.class);
// startActivity(intent); //here you are starting another class..check it
//change it to
startActivity(intent1);
change your InformacijeM.java class:
public class InformacijeM extends AppCompatActivity {
EditText ImeTxt, MasaTxt ;
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_informacije_m);
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
// INICIRANJE VREDNOSTI
EditText ImeTxt = (EditText)findViewById(R.id.ImeInput);
final String str1 = ImeTxt.getText().toString();
EditText MasaTxt = (EditText)findViewById(R.id.MasaInput);
final String str2 = MasaTxt.getText().toString();
save_data(str1,str2);
ImageButton btn = (ImageButton)findViewById(R.id.strelica);
// PREBACIVANJE AKTIVITIJA
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(InformacijeM.this, RezultatM.class);
intent1.putExtra("keyIme", str1);
intent1.putExtra("keyMasa", str2);
Intent intent = new Intent(InformacijeM.this, StanjeM.class);
startActivity(intent);
}
});
}
public void save_data(String s1,String s2){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("keyIme", s1);
editor.putString("keyMasa", s2);
editor.commit();
}
}
The problem is when i get sendBtn from my second activity (called :ClientInterFace) , it always returns null . and even when i want to pass something from my mainActivity(called:loginPage) to the constructor of the second activity , it also returns null!
public class LoginPage extends ActionBarActivity {
Button exitNow;
EditText Username;
TextView conStatus;
EditText Password;
Button LoginBtn;
ProgressBar progressBar;
static String serverAddress = "192.168.1.4";// Set
static int serverPort = 8081;// Set
static String user = "";// received from GUI
static String password = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
exitNow = (Button) findViewById(R.id.exitbtn);
Username = (EditText) findViewById(R.id.username);
conStatus = (TextView) findViewById(R.id.connectionStatus);
Password = (EditText) findViewById(R.id.password);
LoginBtn = (Button) findViewById(R.id.loginBtn);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setEnabled(false);
exitNow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
System.exit(0);
}
});
LoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Runnable r = new Runnable() {
#Override
public void run(){
try {
user = Username.getText().toString();
password = Password.getText().toString();
theRest();
} catch (Exception e) {
e.printStackTrace();
}
}
};
Handler h = new Handler();
h.postDelayed(r, 1500);
}
}
});
}
public void theRest() throws Exception {
final ClientNetworkInterface Connection = new ClientNetworkInterface(serverAddress, serverPort, user, password);
if (Connection.isConnected()) {
Toast.makeText(getApplicationContext(), "Congrats ! You Are channeled through the ClientInterface !", Toast.LENGTH_LONG).show();
final ClientInterFace SecondFrame = new ClientInterFace(user);//this passes "user" to the constructor of ClientInterFace and it gets null .
startActivity(new Intent(LoginPage.this, ClientInterFace.class));
conStatus.setText("Connected!");
progressBar.setVisibility(View.INVISIBLE);
SecondFrame.getSendBtn().setOnClickListener(new View.OnClickListener() {// this is where i get null pointer
#Override
public void onClick(View v) { ...}
// here is second activity , ClientInterFace.
public class ClientInterFace extends ActionBarActivity {
public Button sendBtn;
public EditText Commands;
public Button orm;
public ExtractEditText result;
public String message="";
public String User="";
public ClientInterFace(String user) {
this.User=user;
}
public ClientInterFace(){
}
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.client_layout);
setTitle("Welcome " + User + " !");
TextView textView3=(TextView)findViewById(R.id.textView3);
textView3.setText("Welcome to " + User + " Client Page !");
sendBtn = (Button) findViewById(R.id.sendbtn);
orm=(Button) findViewById(R.id.ORM);
result=(ExtractEditText) findViewById(R.id.extractEditText);
Commands=(EditText) findViewById(R.id.editText);
}
public EditText getTextArea() {
return Commands;
}
public Button getSendBtn() {
return sendBtn;
}
public ExtractEditText getTextArea_1() {
return result;
}
//here is my manifest.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="kooshan.cli" >
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="kooshan.finalap.cli.LoginPage"
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="kooshan.finalap.cli.ClientInterFace"
android:screenOrientation="portrait" />
</application>
</manifest>
//here is main_layout (login_layout)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context="kooshan.finalap.cli.LoginPage"
android:id="#+id/rel">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/linearLayout"
android:weightSum="1"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Username :"
android:id="#+id/textView"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/username"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Password :"
android:id="#+id/textView2"
android:layout_gravity="center_horizontal" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/password"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="exit now ! "
android:id="#+id/exitbtn"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/connectionStatus"
android:layout_weight="0.38"
android:editable="false"
android:gravity="center" />
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_gravity="center_horizontal"
android:indeterminate="false"
android:visibility="invisible" />
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Log in now !"
android:id="#+id/loginBtn"
android:layout_gravity="center_horizontal"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/linearLayout"
android:layout_alignEnd="#+id/linearLayout"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
//here is client_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/secpage"
android:orientation="horizontal"
tools:context="kooshan.finalap.cli.ClientInterFace">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/frame2">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="ORM Page"
android:id="#+id/ORM"
android:layout_gravity="left|top" />
<EditText
android:layout_width="272dp"
android:layout_height="177dp"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/editText"
android:layout_gravity="left|center_vertical"
android:text="SQL>"
android:gravity="top" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="93dp"
android:layout_height="159dp"
android:text="Send Command"
android:id="#+id/sendbtn"
android:layout_gravity="right|center_vertical" />
<android.inputmethodservice.ExtractEditText
android:layout_width="302dp"
android:layout_height="181dp"
android:text="The Result"
android:id="#+id/extractEditText"
android:layout_gravity="left|bottom"
android:inputType="textMultiLine"
android:gravity="top" />
<TextView
android:layout_width="155dp"
android:layout_height="137dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/textView3"
android:layout_gravity="center_horizontal|top"
android:gravity="bottom|center" />
</FrameLayout>
</LinearLayout>
You might have not quite grasped how Activity works in Android. At the moment you are using them like normal Java classes, when they actually differ quite a lot. They might not exist when you normally would suppose a class would exist, which results in the nulls you see. Read up on Activity life cycles.
The correct way to pass variables between Activity classes is using Intents. There is a method called putExtra(..) that you can use to add data that is received by another Activity. Check out the API.
Edit: for example, I am pretty sure this is not a good way to create an activity and will most likely have no effect when you start the Activity with startActivity():
final ClientInterFace SecondFrame = new ClientInterFace(user)
here is my my signupactivity & main activity and their xml
public class SignupActivity extends AppCompatActivity {
protected EditText mUsername;
protected EditText mPassword;
protected EditText mEmail;
protected Button nbutton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
mUsername = (EditText) findViewById(R.id.usernamefield);
mPassword = (EditText) findViewById(R.id.passwordtextfield);
mEmail = (EditText) findViewById(R.id.emailtextfield);
nbutton = (Button) findViewById(R.id.signbutton);
nbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
// Retrieve the text entered from the EditText
String usernametxt = mUsername.getText().toString();
String password = mPassword.getText().toString();
String email= mEmail.getText().toString();
// Force user to fill up the form
if (usernametxt.equals("") && password.equals("")) {
Toast.makeText(getApplicationContext(),
"Please complete the sign up form",
Toast.LENGTH_LONG).show();
} else {
// Save new user data into Parse.com Data Storage
ParseUser newUser = new ParseUser();
newUser.setUsername(usernametxt);
newUser.setPassword(password);
newUser.setEmail(email);
newUser.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
//SUCESS
if (e!= null){
AlertDialog.Builder builder=new AlertDialog.Builder(SignupActivity.this);
builder.setMessage(e.getMessage()).setTitle(R.string.signup_error_title).setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else {
Intent intent= new Intent(SignupActivity.this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
});
}
}
});
}
it was suppose to get the information abt users and go to main activity from signupactivity.the app crashes when it get in put from users and press sign in...
here is the xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.josephvarkey996gmail.test1.SignupActivity" >
<TextView android:text="#string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/usernamefield"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="89dp"
android:hint="#string/username_hint"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/passwordtextfield"
android:layout_centerHorizontal="true"
android:layout_below="#+id/usernamefield"
android:hint="#string/password_hint"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/emailtextfield"
android:hint="#string/email_hint"
android:layout_below="#+id/passwordtextfield"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/signup_hint"
android:id="#+id/signbutton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
here is the main activity code
package com.josephvarkey996gmail.test1;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.parse.Parse;
import com.parse.ParseAnalytics;
import com.parse.ParseUser;
public class MainActivity extends AppCompatActivity {
public static final String TAG = MainActivity.class.getSimpleName();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Parse.enableLocalDatastore(this);
Parse.initialize(this, "XFigOgliUYKi9h5RanLfLkuKU14AG2f2NFQXADKI", "sMQBPkhZV5b74MEGpP3PdQ6eePWo5Y9O8lRcQvBP");
ParseAnalytics.trackAppOpenedInBackground(getIntent());
ParseUser currentUser = ParseUser.getCurrentUser();
if(currentUser==null) {
navigatetologin();
}
if(currentUser!=null)
{
Log.i(TAG ,currentUser.getUsername());
}
// Enable Local Datastore.
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
private void navigatetologin() {
Intent intent = new Intent(this, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
mainactivity xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity" >
<TextView android:text="#string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
android manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.josephvarkey996gmail.test1" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat" >
<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=".SignupActivity"
android:label="#string/title_activity_signup" >
</activity>
<activity
android:name=".LoginActivity"
android:label="#string/title_activity_login" >
</activity>
</application>
</manifest>
We cannot help you until u post your logcat. As I don't have enough reputation to comment, I am writing this in answer.
Most common reason I saw people getting this error is:
They copy -paste this line from another class
R.id.usernamefield
So it will try to run the usernamefield of their other class which is not present here(note: eclipse will automatically import so they didn't get compilation errors). So to resolve your error you should delete the import and write proper R.id.xyz
But this is only shot in the dark until we see your logcat.
I am here to seek some help with my code which i am facing a dead end road with. I'm trying to pass values from screen1.java using Intent to screen2.java. Passing the values is fine and I managed to get through it; however, when I check using if statement the program crash down. Here are my files, plzzzzzzzzzzz help
screen1.java
package test.android;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class screen1 extends Activity
{
static String strKey = "Hello";
static final String strValue = "Hello";
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.screen1);
//** button A
Button A = (Button) findViewById(R.id.btnClickA);
A.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(screen1.this, screen2.class);
strKey = "NAME";
i.setClassName("packageName", "packageName.IntentClass");
String term = "Hello";
i.putExtra("packageName.term", term);
//i.putExtra(strKey, strValue);
startActivity(i);
}
});
//**
//** button B
Button B = (Button) findViewById(R.id.btnClickB);
B.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(screen1.this, screen3.class);
startActivity(i);
}
});
//**
}
}
screen2.java
package test.android;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class screen2 extends Activity
{
public void onCreate(Bundle icicle)
{
Bundle extras = getIntent().getExtras();
String term = extras.getString("packageName.term");
System.out.println("--- Name is -->"+ term);
if(term.equalsIgnoreCase("Hello") || term.equalsIgnoreCase("Name")){
super.onCreate(icicle);
setContentView(R.layout.screen3);
Button b = (Button) findViewById(R.id.btnClick3);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
setResult(RESULT_OK);
finish();
}
});
} else {
super.onCreate(icicle);
setContentView(R.layout.screen2);
Button b = (Button) findViewById(R.id.btnClick2);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
setResult(RESULT_OK);
finish();
}
});
}
// DOES NOT WORK !!!!!!!!!
System.out.println("--- Name is -->"+ term);
}
}
Layouts:
screen1.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="You are in the first Screen"
/>
<Button
android:id ="#+id/btnClickA"
android:background="#drawable/sleep0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Open Screen 2"
/>
<Button
android:id ="#+id/btnClickB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Open Screen 3"
/>
<ImageView android:id="#+id/icon" android:layout_width="wrap_content"
android:layout_height="fill_parent" android:src="#drawable/icon"
android:layout_gravity="center"/>
</LinearLayout>
screen2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="You are in Screen 2"
/>
<Button
android:id ="#+id/btnClick2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close"
/>
</LinearLayout>
screen3.xml
<?xml version="1.0" encoding="utf-8"?>
<!-- ScrollView: will allow the layout to be scroll Up/Down and Left/right -->
<ScrollView
android:id="#+id/widget54"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scrollbars="vertical"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="You are in Screen 3"
/>
<Button
android:id ="#+id/btnClick3"
android:background="#drawable/sss"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close"
/>
<ImageView android:id="#+id/sssq" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:src="#drawable/sssq"
android:layout_gravity="center" />
</LinearLayout>
</ScrollView>
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="test.android">
<application android:icon="#drawable/icon">
<activity android:name="screen1"
android:label="SCREEN 1">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="screen2"
android:label="SCREEN 2">
</activity>
<activity android:name="screen3"
android:label="SCREEN 3">
</activity>
</application>
</manifest>
=====
The error is caused by these lines of code in screen2.java:
if(term.equalsIgnoreCase("Hello") || term.equalsIgnoreCase("Name")){
super.onCreate(icicle);
setContentView(R.layout.screen3);
Button b = (Button) findViewById(R.id.btnClick3);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
setResult(RESULT_OK);
finish();
}
});
}
else {
super.onCreate(icicle);
setContentView(R.layout.screen2);
Button b = (Button) findViewById(R.id.btnClick2);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
setResult(RESULT_OK);
finish();
}
});
}
**notice if I get rid of the entire IF statement and go with only the ELSE the program works fine.
i.setClassName("packageName", "packageName.IntentClass") is not required, if you are passing information to Intent constructor. Btw Is your Screen3 call working fine ?
You're passing the data incorrectly, try this:
public void onClick(View arg0) {
Intent i = new Intent(screen1.this, screen2.class);
strKey = "NAME";
//NO NEED FOR THIS, REMOVE -> i.setClassName("packageName", "packageName.IntentClass");
String term = "Hello";
//Add your string to a bundle:
Bundle b = new Bundle();
b.putString("packageName.term", term);
//Then add the bundle to your intent
i.putExtra(b);
//i.putExtra(strKey, strValue);
startActivity(i);
}
The way you retrieve it in screen2 activity is fine, I would just check if term is null:
if(term != null && (term.equalsIgnoreCase("Hello") || term.equalsIgnoreCase("Name"))){
...