I'm trying to design a times table testing app, the theory is that the user is presented with a screen with 12 buttons to select from.
When he presses a button it opens a new class testing him with the number he chose. There are 4 main files:
MainActivity.java
activity_main.xml
Times.java
activity_times.java
Currently the class view that comes up to test the user (activity_times.xml), just contains three text views:
"HI" id=textView
"" (empty to be edited in the java class) id=TextOut
"Under development...." id=textView2
The first and last text views are not important, they'll be removed later on.
In the MainActivity.java class I declared a shared variable
public int numberClicked;
and then told the buttons to set the variable to a certain number:
button2 = findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numberClicked = 2;
openTestPage();
}
});
and then on the Times.java class I told it to import it and the empty output text view:
private MainActivity MA;
private int SubjectNumber = MA.numberClicked;
private final TextView OutputText = findViewById(R.id.TextOut);
and then to set the text view to the imported variable:
OutputText.setText("You chose the number " + SubjectNumber);
The output I want is that on the screen is that the TextOut text view shows, for example if the user presses the button with the number "2" on it: "You chose the number 2".
But instead of that, the app crashes when the second class view launches :(
To stop it from crashing I have to comment out the following code:
private MainActivity MA;
private int SubjectNumber = MA.numberClicked;
private final TextView OutputText = findViewById(R.id.TextOut);
If I uncomment only one of the three lines it will still crash.
I looked in the logcat and saw something interesting:
2020-08-23 15:20:18.553 6537-6537/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.ma, PID: 6537
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.ma/com.example.ma.Times}: java.lang.NullPointerException: Attempt to read from field 'int com.example.ma.MainActivity.numberClicked' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2844)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3049)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1809)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6680)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Caused by: java.lang.NullPointerException: Attempt to read from field 'int com.example.ma.MainActivity.numberClicked' on a null object reference
at com.example.ma.Times.<init>**(Times.java:13)**
at java.lang.Class.newInstance(Native Method)
at android.app.AppComponentFactory.instantiateActivity(AppComponentFactory.java:69)
at androidx.core.app.CoreComponentFactory.instantiateActivity(CoreComponentFactory.java:41)
at android.app.Instrumentation.newActivity(Instrumentation.java:1215)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2832)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3049)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1809)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6680)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
Every thing that came out of the logcat you will find here.
My AndroidManefest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.ma">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="Times Practice"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".Times">
</activity>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
</application>
</manifest>
My MainActivity.java
package com.example.ma;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
public int numberClicked;
private Button button2;
private Button button3;
private Button button4;
private Button button5;
private Button button6;
private Button button7;
private Button button8;
private Button button9;
private Button button10;
private Button button11;
private Button button12;
private Button button13;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button2 = findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numberClicked = 2;
openTestPage();
}
});
button3 = findViewById(R.id.button3);
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numberClicked = 3;
openTestPage();
}
});
button4 = findViewById(R.id.button4);
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numberClicked = 4;
openTestPage();
}
});
button5 = findViewById(R.id.button5);
button5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numberClicked = 5;
openTestPage();
}
});
button6 = findViewById(R.id.button6);
button6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numberClicked = 6;
openTestPage();
}
});
button7 = findViewById(R.id.button7);
button7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numberClicked = 7;
openTestPage();
}
});
button8 = findViewById(R.id.button8);
button8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numberClicked = 8;
openTestPage();
}
});
button9 = findViewById(R.id.button9);
button9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numberClicked = 9;
openTestPage();
}
});
button10 = findViewById(R.id.button10);
button10.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numberClicked = 10;
openTestPage();
}
});
button11 = findViewById(R.id.button11);
button11.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numberClicked = 11;
openTestPage();
}
});
button12 = findViewById(R.id.button12);
button12.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numberClicked = 12;
openTestPage();
}
});
button13 = findViewById(R.id.button13);
button13.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numberClicked = 13;
openTestPage();
}
});
}
public void openTestPage() {
Intent intent = new Intent(this, Times.class);
startActivity(intent);
}
}
My activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/Instructions"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/acme"
android:gravity="center"
android:text="Choose the number you want to practice your times tables with....."
android:textAppearance="#style/TextAppearance.AppCompat.Large"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.051" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/architects_daughter"
android:text="2"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/button5"
app:layout_constraintEnd_toStartOf="#+id/button3"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/Instructions" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/architects_daughter"
android:text="3"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/button6"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.501"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/Instructions" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/architects_daughter"
android:text="4"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/button7"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.493"
app:layout_constraintStart_toEndOf="#+id/button3"
app:layout_constraintTop_toBottomOf="#+id/Instructions" />
<Button
android:id="#+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/architects_daughter"
android:text="5"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/button6"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.499" />
<Button
android:id="#+id/button6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/architects_daughter"
android:text="6"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.501"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.499" />
<Button
android:id="#+id/button7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/architects_daughter"
android:text="7"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.493"
app:layout_constraintStart_toEndOf="#+id/button6"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/button8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/architects_daughter"
android:text="8"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/button11"
app:layout_constraintEnd_toStartOf="#+id/button9"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/button5" />
<Button
android:id="#+id/button9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/architects_daughter"
android:text="9"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/button12"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/button6" />
<Button
android:id="#+id/button10"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="#font/architects_daughter"
android:text="10"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/button13"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/button9"
app:layout_constraintTop_toBottomOf="#+id/button7" />
<Button
android:id="#+id/button11"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="80dp"
android:fontFamily="#font/architects_daughter"
android:text="11"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/button12"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/button12"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="80dp"
android:fontFamily="#font/architects_daughter"
android:text="12"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/button13"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="80dp"
android:fontFamily="#font/architects_daughter"
android:text="13"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/button12" />
</androidx.constraintlayout.widget.ConstraintLayout>
My Times.java:
package com.example.ma;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class Times extends AppCompatActivity {
private MainActivity MA;
private int SubjectNumber = MA.numberClicked;
private final TextView OutputText = findViewById(R.id.TextOut);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_times);
OutputText.setText("You chose the number " + SubjectNumber);
}
}
My activity_times.xml:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_height="match_parent"
tools:context=".Times">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Under development...."
android:textSize="28sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.696" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="HI"
android:textSize="100sp"
app:layout_constraintBottom_toTopOf="#+id/TextOut"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.501"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/TextOut"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="316dp"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
You shouldn't try to directly access an Activity from another Activity. In Android, you add the data you want to share with another Activity onto an Intent. You also shouldn't try to obtain a view outside of the Activity lifecycle. Your findViewById() should be moved to the Activity's onCreate().
In your first Activity's openTestPage():
Intent intent = new Intent(this, Times.class);
// Add the value you want to pass to the other Activity
// to the Intent
intent.putExtra("NUMBER_CLICKED", numberClicked);
startActivity(intent);
Your second Activity should look something like this:
public class Times extends AppCompatActivity {
private int SubjectNumber;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_times);
// Access your views here
TextView OutputText = findViewById(R.id.TextOut);
// Retrieve the value passed into the Intent
// (The 0 is a default value to fallback on. You can use another value.)
SubjectNumber = getIntent().getIntExtra("NUMBER_CLICKED", 0);
OutputText.setText("You chose the number " + SubjectNumber);
}
}
You can't directly pass the data from one activity to another you just need to pass through intent or bundle. Here I am updating your code.
MainActivity.java
public void openTestPage(int numberClicked) {
Intent intent = new Intent(this, Times.class);
intent.putExtra("intVariableName", numberClicked);
startActivity(intent);
}
Times.java
Intent intent = getIntent();
int intValue = intent.getIntExtra("intVariableName", 0);
OutputText.setText("You chose the number " + intValue);
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");
}
}
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Null pointer Exception - findViewById()
(12 answers)
Closed 4 years ago.
I have searched for an answer that works for me but have not come across anything that helped.
My problem is that I am linking an ImageButton to another activity, however when clicked on throws a NullPointerException
Here is the MainActivity class:
package com.example.gpp2;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class MainActivity extends AppCompatActivity {
ImageButton addButton;
ImageButton loginButton;
ImageButton offerButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addButton = (ImageButton) findViewById(R.id.imageButton);
addButton.setOnClickListener(new View.OnClickListener() {
// When the button is pressed/clicked, it will run the code below
#Override
public void onClick(View view) {
// Intent is what you use to start another activity
Intent intent = new Intent(MainActivity.this, AddPage.class);
intent.putExtra("keyWord", R.drawable.add);
startActivity(intent);
}
});
loginButton = (ImageButton) findViewById(R.id.imageButton5);
loginButton.setOnClickListener(new View.OnClickListener() {
// When the button is pressed/clicked, it will run the code below
#Override
public void onClick(View view) {
// Intent is what you use to start another activity
Intent intent = new Intent(MainActivity.this, loginH.class);
intent.putExtra("keyWord", R.drawable.login);
startActivity(intent);
}
});
offerButton = (ImageButton) findViewById(R.id.imageButton4);
offerButton.setOnClickListener(new View.OnClickListener() {
// When the button is pressed/clicked, it will run the code below
#Override
public void onClick(View view) {
// Intent is what you use to start another activity
Intent intent = new Intent(MainActivity.this, OfferPage.class);
intent.putExtra("keyWord", R.drawable.moneybag);
startActivity(intent);
}
});
}
}
Here is the activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_height="match_parent"
android:background="#drawable/logo"
tools:context=".MainActivity">
<TextView
android:id="#+id/NCard"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:text="#string/NCard"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.526"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.024" />
<android.support.constraint.Guideline
android:id="#+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_begin="58dp" />
<android.support.constraint.Guideline
android:id="#+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_begin="724dp" />
<ImageButton
android:id="#+id/imageButton"
android:layout_width="66dp"
android:layout_height="50dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:background="#null"
android:scaleType="centerInside"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
app:srcCompat="#drawable/add" />
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="87dp"
android:layout_height="69dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:background="#null"
android:scaleType="centerInside"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.025"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.998"
app:srcCompat="#drawable/creditcardspayment" />
<ImageButton
android:id="#+id/imageButton3"
android:layout_width="87dp"
android:layout_height="69dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:background="#null"
android:scaleType="centerInside"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.353"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.998"
app:srcCompat="#drawable/bell" />
<ImageButton
android:id="#+id/imageButton4"
android:layout_width="87dp"
android:layout_height="69dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:background="#null"
android:scaleType="centerInside"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.691"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
app:srcCompat="#drawable/moneybag" />
<ImageButton
android:id="#+id/imageButton5"
android:layout_width="87dp"
android:layout_height="69dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:background="#null"
android:scaleType="centerInside"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0"
app:srcCompat="#drawable/login" />
<android.support.constraint.Guideline
android:id="#+id/guideline4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/black"
android:orientation="horizontal"
app:layout_constraintGuide_begin="637dp" />
</android.support.constraint.ConstraintLayout>
Here is the AddPaje class:
package com.example.gpp2;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class AddPage extends MainActivity {
Button addButton;
ImageButton backButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addpage);
backButton = (ImageButton) findViewById(R.id.imageButton11);
backButton.setOnClickListener(new View.OnClickListener() {
// When the button is pressed/clicked, it will run the code below
#Override
public void onClick(View view) {
// Intent is what you use to start another activity
Intent intent = new Intent(AddPage.this, MainActivity.class);
startActivity(intent);
}
});
addButton = (Button) findViewById(R.id.button);
addButton.setOnClickListener(new View.OnClickListener() {
// When the button is pressed/clicked, it will run the code below
#Override
public void onClick(View view) {
// Intent is what you use to start another activity
Intent intent = new Intent(AddPage.this, NewCard.class);
startActivity(intent);
}
});
}
}
this is all errors in Run
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.gpp2, PID: 21722
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.gpp2/com.example.gpp2.AddPage}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.example.gpp2.AddPage.onCreate(AddPage.java:22)
at android.app.Activity.performCreate(Activity.java:7009)
at android.app.Activity.performCreate(Activity.java:7000)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1214)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2731)
you can pass byte array and get byte array and then make a bitmap :
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] b = baos.toByteArray();
Intent intent = new Intent(this, ActivityB.class);
intent.putExtra("picture", b);
startActivity(intent);
In Activity B you receive intent with byte array (decoded picture) and apply it as source to ImageView:
Bundle extras = getIntent().getExtras();
byte[] b = extras.getByteArray("picture");
`
Bitmap bmp = BitmapFactory.decodeByteArray(b, 0, b.length);
`ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageBitmap(bmp);
I am working on an App in Android Studios and what I want it to do is it should ask the user would you like to either to listen to Music or watch Videos after they decide what mood they are in. The problem is that when I click the mood it goes straight to the video and when I click the back button it then asks if they would like to music or videos. So it needs to be the other way around. I am working on this in Android Studios. I will paste the code down below.
This is the code for the MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button0 = (Button) findViewById(R.id.HappyButton);
Button button1 = (Button) findViewById(R.id.SadButton);
Button button2 = (Button) findViewById(R.id.MellowButton);
Button button3 = (Button) findViewById(R.id.MotivatedButton);
Button button4 = (Button) findViewById(R.id.AngryButton);
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myintent = new Intent(MainActivity.this,theOptionsPage.class);
startActivity(myintent);
openHappy();
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openSad();
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openMello();
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openMotivated();
}
});
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openAngry();
}
});
}
public void showMe(View v){
String button_text;
button_text = ((Button) v).getText().toString();
if(button_text.equals("HAPPY")){
Intent intent = new Intent(this,theOptionsPage.class);
startActivity(intent);
}
}
#Override
public void onClick(View view) {
}
public void openHappy(){
Intent intent = new Intent(this,YoutubeHappy.class);
startActivity(intent);
}
public void openSad(){
Intent sadintent = new Intent(this,YoutubeSad.class);
startActivity(sadintent);
}
public void openMello(){
Intent mellowintent = new Intent(this,YoutubeMellow.class);
startActivity(mellowintent);
}
public void openMotivated(){
Intent motivatedintent = new Intent(this,YoutubeMotivated.class);
startActivity(motivatedintent);
}
public void openAngry(){
Intent angryintent = new Intent(this,YoutubeAngry.class);{
startActivity(angryintent);
}
}
}
This is the activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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:layout_height="match_parent"
tools:context="com.code.mohamedali.hackathon2018.MainActivity">
<Button
android:id="#+id/HappyButton"
android:layout_width="141dp"
android:layout_height="75dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="32dp"
android:text="HAPPY"
android:onClick="showMe"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/FeelingView" />
<Button
android:id="#+id/SadButton"
android:layout_width="141dp"
android:layout_height="75dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="SAD"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/HappyButton" />
<Button
android:id="#+id/AngryButton"
android:layout_width="141dp"
android:layout_height="75dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="ANGRY"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/SadButton" />
<Button
android:id="#+id/MotivatedButton"
android:layout_width="141dp"
android:layout_height="75dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="MOTIVATED"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/AngryButton" />
<Button
android:id="#+id/MellowButton"
android:layout_width="141dp"
android:layout_height="75dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="12dp"
android:text="MELLOW"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.513"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/MotivatedButton" />
<TextView
android:id="#+id/FeelingView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="How Are You Feeling Today?"
android:textAlignment="center"
android:textSize="30sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Below is the OptionsPage Code and XML
public class theOptionsPage extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options_page);
Button button1 = (Button) findViewById(R.id.MusicButton);
Button button2 = (Button) findViewById(R.id.VideoButton);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent in1 = new Intent( MainActivity.this , theOptionsPage.class);
// startActivity(in1);
}
});
}
}
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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:layout_height="match_parent">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="44dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Would You Like Muisc or Videos"
android:textAlignment="center"
android:textAllCaps="false"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.172" />
<Button
android:id="#+id/MusicButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginStart="80dp"
android:layout_marginTop="116dp"
android:text="Music"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView"
app:layout_constraintVertical_bias="0.0" />
<Button
android:id="#+id/VideoButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="72dp"
android:text="Videos"
app:layout_constraintBaseline_toBaselineOf="#+id/MusicButton"
app:layout_constraintEnd_toEndOf="parent" />
</android.support.constraint.ConstraintLayout>
Hi if you see your code in button0 click event:
button0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myintent = new Intent(MainActivity.this,theOptionsPage.class);
startActivity(myintent);
openHappy();
}
});
See that after starting the theOptionsPage activty, immediately u call openHappy(); This is why it starts the "theOptionPage" and then immediately starts the "YoutubeHappy" activity.
So remove the openHappy() call inside the click listener and then start the activity from "theOptionPage"
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)
my code is to change edittext to bold or italic .
this code to write a text in editText and send it to another layout when touch in image1
this has intent to take text and size of text
i want another intent to take the bold or italic also .
public class Graduation extends ActionBarActivity {
Button button;
ImageView imageView ;
Spinner spinner;
int fontSizeInt;
String[]items = { "12", "16", "18", "20", "24", "28" , "30" };
int fontSizeFamily;
EditText et;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.graduation);
spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, items);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int position = spinner.getSelectedItemPosition();
try
{
fontSizeInt = Integer.parseInt(items[position]);
}
catch (NumberFormatException e)
{
fontSizeInt = 12; // Default size.
}
et.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float) fontSizeInt);
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
addListenerOnImageg1() ;
addListenerOnButton1();
addListenerOnButton2();
et = (EditText) findViewById(R.id.et);
}
public void addListenerOnButton1() {
final Context context = this;
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
et.setTypeface(null,Typeface.BOLD);
}
}); }
public void addListenerOnButton2() {
final Context context = this;
button = (Button) findViewById(R.id.button2);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
et.setTypeface(null,Typeface.ITALIC);
}
}); }
public void addListenerOnImageg1() {
final Context context = this;
imageView = (ImageView) findViewById(R.id.g1);
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, g1.class);
startActivity(intent);
Intent intent1 = new Intent(context , g1.class);
intent1.putExtra("fn" , et.getText().toString());
intent1.putExtra("font_size", fontSizeInt);
startActivity(intent1);
// here is the intent I want to take a style also to another layout
}
}); }
also i have .xml file which has all the content i want ..
something like this
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/backf"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter your Text Here : "
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<TableLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TableRow>
<Spinner
android:id="#+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:drawable/btn_dropdown"
android:spinnerMode="dropdown" />
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textStyle="bold"
android:text="B" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="italic"
android:text="I" />
</TableRow>
</TableLayout>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="choose your card : "
android:textAppearance="?android:attr/textAppearanceLarge" />
<ImageView
android:id="#+id/g1"
android:layout_width="122dp"
android:layout_height="111dp"
android:clickable="true"
android:onClick="onClick"
android:src="#drawable/g1" />
<ImageView
android:id="#+id/g2"
android:layout_width="122dp"
android:layout_height="111dp"
android:clickable="true"
android:onClick="onClick"
android:src="#drawable/g2" />
<ImageView
android:id="#+id/g3"
android:layout_width="122dp"
android:layout_height="111dp"
android:clickable="true"
android:onClick="onClick"
android:src="#drawable/g3" />
<ImageView
android:id="#+id/g4"
android:layout_width="122dp"
android:layout_height="111dp"
android:clickable="true"
android:onClick="onClick"
android:src="#drawable/g4" />
<ImageView
android:id="#+id/g5"
android:layout_width="122dp"
android:layout_height="111dp"
android:clickable="true"
android:onClick="onClick"
android:src="#drawable/g5" />
<ImageView
android:id="#+id/g6"
android:layout_width="122dp"
android:layout_height="111dp"
android:clickable="true"
android:onClick="onClick"
android:src="#drawable/g6" />
<ImageView
android:id="#+id/g7"
android:layout_width="122dp"
android:layout_height="111dp"
android:clickable="true"
android:onClick="onClick"
android:src="#drawable/g7" />
</LinearLayout>
</ScrollView>
so my text goes to another layout with no change so when i click bold button the change happen on editText but when i click image the text go to image1 layout without bold