How to fix Null Pointer Exception error in Java? - android-studio

My app keeps crashing when I try to log in (after LoginActivity file). Here's the code. I"d really appreciate some help with this.
MainActivity (opens the register/login screen)
package com.jovanovic.stefan.sqlitetutorial;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText username, password, repassword;
Button signup, signin;
DBHelper DB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
repassword = (EditText) findViewById(R.id.repassword);
signup = (Button) findViewById(R.id.btnsignup);
signin = (Button) findViewById(R.id.btnsignin);
DB = new DBHelper(this);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String user = username.getText().toString();
String pass = password.getText().toString();
String repass = repassword.getText().toString();
if(user.equals("")||pass.equals("")||repass.equals(""))
Toast.makeText(MainActivity.this, "Please enter all the fields", Toast.LENGTH_SHORT).show();
else{
if(pass.equals(repass)){
Boolean checkuser = DB.checkusername(user);
if(checkuser==false){
Boolean insert = DB.insertData(user, pass);
if(insert==true){
Toast.makeText(MainActivity.this, "Registered successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
startActivity(intent);
}else{
Toast.makeText(MainActivity.this, "Registration failed", Toast.LENGTH_SHORT).show();
}
}
else{
Toast.makeText(MainActivity.this, "User already exists! please sign in", Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(MainActivity.this, "Passwords not matching", Toast.LENGTH_SHORT).show();
}
} }
});
signin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
}
});
}
}
LoginActivity (once registered then proceed to login)
package com.jovanovic.stefan.sqlitetutorial;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity {
EditText username, password;
Button btnlogin;
DBHelper DB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.username1);
password = (EditText) findViewById(R.id.password1);
btnlogin = (Button) findViewById(R.id.btnsignin1);
DB = new DBHelper(this);
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String user = username.getText().toString();
String pass = password.getText().toString();
if(user.equals("")||pass.equals(""))
Toast.makeText(LoginActivity.this, "Please enter all the fields", Toast.LENGTH_SHORT).show();
else{
Boolean checkuserpass = DB.checkusernamepassword(user, pass);
if(checkuserpass==true){
Log.d("mytag","1");
Toast.makeText(LoginActivity.this, "Sign in successfull", Toast.LENGTH_SHORT).show();
Log.d("mytag","2");
Intent intent = new Intent(getApplicationContext(), HomeActivity.class);
Log.d("mytag","3");
startActivity(intent);
}else{
Toast.makeText(LoginActivity.this, "Invalid Credentials", Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
HomeActivity (this should open the main screen of the app. The app has a add button which adds items using recyclerview)
package com.jovanovic.stefan.sqlitetutorial;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.ArrayList;
public class HomeActivity extends Activity {
RecyclerView recyclerView;
FloatingActionButton add_button;
ImageView empty_imageview;
TextView no_data;
MyDatabaseHelper myDB;
ArrayList<String> book_id, book_title, book_author, book_pages;
CustomAdapter customAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
add_button = findViewById(R.id.add_button);
empty_imageview = findViewById(R.id.empty_imageview);
no_data = findViewById(R.id.no_data);
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(HomeActivity.this, AddActivity.class);
startActivity(intent);
}
});
myDB = new MyDatabaseHelper(HomeActivity.this);
book_id = new ArrayList<>();
book_title = new ArrayList<>();
book_author = new ArrayList<>();
book_pages = new ArrayList<>();
storeDataInArrays();
customAdapter = new CustomAdapter(HomeActivity.this,this, book_id, book_title, book_author,
book_pages);
recyclerView.setAdapter(customAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(HomeActivity.this));
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1){
recreate();
}
}
void storeDataInArrays(){
Cursor cursor = myDB.readAllData();
if(cursor.getCount() == 0){
empty_imageview.setVisibility(View.VISIBLE);
no_data.setVisibility(View.VISIBLE);
}else{
while (cursor.moveToNext()){
book_id.add(cursor.getString(0));
book_title.add(cursor.getString(1));
book_author.add(cursor.getString(2));
book_pages.add(cursor.getString(3));
}
empty_imageview.setVisibility(View.GONE);
no_data.setVisibility(View.GONE);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId() == R.id.delete_all){
confirmDialog();
}
return super.onOptionsItemSelected(item);
}
void confirmDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Delete All?");
builder.setMessage("Are you sure you want to delete all Data?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MyDatabaseHelper myDB = new MyDatabaseHelper(HomeActivity.this);
myDB.deleteAllData();
//Refresh Activity
Intent intent = new Intent(HomeActivity.this, HomeActivity.class);
startActivity(intent);
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.create().show();
}
}
Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jovanovic.stefan.sqlitetutorial">
<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=".UpdateActivity"
android:parentActivityName=".HomeActivity"/>
<activity android:name=".HomeActivity"
android:label="GDSC Items App"/>
<activity android:name=".LoginActivity"
android:label="GDSC Items App"/>
<activity
android:name=".AddActivity"
android:label="Add Item"
android:parentActivityName=".HomeActivity" />
<activity
android:name=".MainActivity"
android:label="GDSC Items App">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Error log
2022-01-27 20:31:01.505 3354-3354/com.jovanovic.stefan.sqlitetutorial E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.jovanovic.stefan.sqlitetutorial, PID: 3354
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jovanovic.stefan.sqlitetutorial/com.jovanovic.stefan.sqlitetutorial.HomeActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.floatingactionbutton.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
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:1831)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.material.floatingactionbutton.FloatingActionButton.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.jovanovic.stefan.sqlitetutorial.HomeActivity.onCreate(HomeActivity.java:45)
at android.app.Activity.performCreate(Activity.java:7224)
at android.app.Activity.performCreate(Activity.java:7213)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2926)

Make sure you setting the correct layout inside the setContentView() method
For example:
setContentView(R.layout.activity_home);

Related

Activity not moving to another activty in android studio

package com.example.bookapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Patterns;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.example.bookapp.databinding.ActivityLoginBinding;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class LoginActivity extends AppCompatActivity {
private ActivityLoginBinding binding;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
private Button BtnLogin;
private EditText TxtEmail;
private EditText TxtPassword;
private TextView singUp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
firebaseAuth = firebaseAuth.getInstance();
progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Please wait");
progressDialog.setCanceledOnTouchOutside(false);
BtnLogin =(Button) findViewById(R.id.loginBtn);
singUp =(TextView) findViewById(R.id.noAccountTv);
singUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Intent i = new Intent(LoginActivity.this, RegisterActivity.class);
startActivity(i);
}
});
BtnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
validateData();
}
});
}
private String email = "", password = "";
private void validateData() {
TxtEmail =(EditText) findViewById(R.id.emailet);
email =TxtEmail.getText().toString().trim();
TxtPassword = (EditText) findViewById(R.id.passwordet);
password = TxtPassword.getText().toString().trim();
if(!Patterns.EMAIL_ADDRESS.matcher(email).matches())
{
Toast.makeText(this, "Invalid Email Pattern..!", Toast.LENGTH_SHORT).show();
}
else if(TextUtils.isEmpty(password))
{
Toast.makeText(this,"Please enter password",Toast.LENGTH_SHORT).show();
}
else
{
loginUser();
}
}
private void loginUser()
{
progressDialog.setMessage("Logging In");
progressDialog.show();
firebaseAuth.signInWithEmailAndPassword(email,password)
.addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
checkUser();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure( Exception e) {
progressDialog.dismiss();
Toast.makeText(LoginActivity.this,""+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
private void checkUser()
{
progressDialog.setMessage("Checking User..");
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
ref.child(firebaseUser.getUid())
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot)
{
progressDialog.dismiss();
String userType = ""+snapshot.child("userType").getValue();
if(userType.equals("user"))
{
Intent i = new Intent(LoginActivity.this,DashboardUserActivity.class);
startActivity(i);
finish();
}
else if(userType.equals("admin"))
{
Intent i = new Intent(LoginActivity.this,DashboardAdminActivity.class);
startActivity(i);
finish();
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
}
}
Application is unable to move to the DashboardAdminActivity/DashboardUserActivity while progressbar is showing & email and password validation is also working, but it's not going to the next activities according to the "usertype".
I also tried intent another way, but it's not working, if you guys can find any error/correction in my code, it would be appreciated.

About menu crash after press it

I do not know what error I have. I already put MainActivity between new Intent and this.
This is my mainactivity.java
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.:
Intent intent = new Intent(MainActivity.this, AboutActivity.class);
startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
This is menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/about"
android:title="About"
app:showAsAction="never"/>
</menu>
This is AboutActivity.java
package com.example.zakatcalculator;
import android.os.Bundle;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class AboutActivity extends AppCompatActivity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_about);
textView = findViewById(R.id.textViewLink);
textView.setMovementMethod(LinkMovementMethod.getInstance());
}
}
And this is AndroidManifest.xml
<activity
android:name=".AboutActivity"
android:exported="false">
</activity>
When I press about button, then its crash.
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()){
case R.id.about:
Intent intent = new Intent(MainActivity.this, AboutActivity.class);
startActivity(intent);
break;
}
return super.onOptionsItemSelected(item);
}
replace R.id. to this R.id.about and try again.

Open new activity by Clicking button in a Fragment

I'm currently working on a mobile app as a final project for my course. I have these two fragments inside a ViewPager2 controlled by a TabLayout. There are buttons inside of these fragments.
The first frag contains 2 buttons. The other frag has only one button. I want them to open an activity but the problem is when I run the app, these buttons won't work. They didn't open the other activity.
Login Fragment
package com.example.biowit;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.blogspot.atifsoftwares.animatoolib.Animatoo;
public class LoginTabFragment extends Fragment {
EditText email, password;
Button btn_login, btn_forpass;
TextView textView;
float v=0;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.login_fragment, container, false);
email = root.findViewById(R.id.input_LI_email);
password = root.findViewById(R.id.input_LI_pass);
btn_forpass = root.findViewById(R.id.btn_FPass);
btn_login = root.findViewById(R.id.btn_LIn);
email.setTranslationX(800);
password.setTranslationX(800);
btn_forpass.setTranslationX(800);
btn_login.setTranslationX(800);
email.setAlpha(v);
password.setAlpha(v);
btn_forpass.setAlpha(v);
btn_login.setAlpha(v);
email.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
password.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
btn_forpass.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
btn_login.animate().translationX(0).alpha(1).setDuration(800).setStartDelay(300).start();
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), HomeScreen.class);
startActivity(intent);
Animatoo.animateFade(getActivity());
getActivity().finish();
}
});
return root;
}
}
LoginScreen (where the fragment locates)
package com.example.biowit;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.viewpager.widget.ViewPager;
import androidx.viewpager2.widget.ViewPager2;
import android.os.Bundle;
import com.google.android.material.tabs.TabItem;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
public class
LoginScreen extends AppCompatActivity {
TabLayout tabLayout;
ViewPager2 viewPager;
float v=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_screen);
tabLayout = findViewById(R.id.tab_layout);
viewPager = findViewById(R.id.view_pager);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
LoginAdapter login_adapter = new LoginAdapter(this);
viewPager.setAdapter(login_adapter);
new TabLayoutMediator(tabLayout, viewPager,
new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
switch (position){
case 0:
tab.setText("LOGIN");
break;
case 1:
tab.setText("SIGNUP");
break;
}
}
}).attach();
tabLayout.setAlpha(v);
}
}
Here's the error log(?)
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.biowit, PID: 18551
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.biowit/com.example.biowit.HomeScreen}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.hide()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3754)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3912)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2319)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:239)
at android.app.ActivityThread.main(ActivityThread.java:8212)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:626)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1016)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.hide()' on a null object reference
at com.example.biowit.HomeScreen.onCreate(HomeScreen.java:22)
at android.app.Activity.performCreate(Activity.java:8119)
at android.app.Activity.performCreate(Activity.java:8103)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1359)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3727)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3912) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:85) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2319) 
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:239) 
at android.app.ActivityThread.main(ActivityThread.java:8212) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:626) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1016) 
HomeScreen (Activity that supposedly open when clicking the button)
package com.example.biowit;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class HomeScreen extends AppCompatActivity {
Button Chap1_btn, Achieve_btn, HowToPlay_btn, LogOut_btn, Settings_btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
getSupportActionBar().hide(); // hides the action bar.
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
Chap1_btn = findViewById(R.id.btn_Chap1);
Achieve_btn = findViewById(R.id.btn_Achievements);
HowToPlay_btn = findViewById(R.id.btn_HowToPlay);
LogOut_btn = findViewById(R.id.btn_Logout);
Settings_btn = findViewById(R.id.btn_Settings);
Chap1_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent open_Chap1 = new Intent(getApplicationContext(), LessonScreen.class);
startActivity(open_Chap1);
}
});
Achieve_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent open_Achievements = new Intent(getApplicationContext(), Achievements.class);
}
});
HowToPlay_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Intent open_HowToPlay = new Intent(getApplicationContext().HowToPlay.class);
}
});
LogOut_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Settings_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent open_Settings = new Intent(getApplicationContext(), Settings.class);
startActivity(open_Settings);
}
});
}
}
getSupportActionBar().hide(); is what's causing the error. You have added it before
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
So it's trying to execute it before the activity is initialised.
Add it after the above 2 lines and it should work.

Encrypted Bluetooth chat communication

Having issues with the app, shuts down any time I click on the chat button. I just submitted my manifest, gradle , xml, and the mainactivity to check what really went wrong. Thanks
I have an error from the logcat
GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1.
2021-06-26 05:10:29.573 24952-24952/c.bawp.securemessenger D/AndroidRuntime: Shutting down VM
2021-06-26 05:10:29.587 24952-24952/c.bawp.securemessenger E/AndroidRuntime: FATAL EXCEPTION: main
Process: c.bawp.securemessenger, PID: 24952
android.content.ActivityNotFoundException: Unable to find explicit activity class {c.bawp.securemessenger/c.bawp.securemessenger.ChatController}; have you declared this activity in your AndroidManifest.xml?
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:2005)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1673)
at android.app.Activity.startActivityForResult(Activity.java:4586)
at androidx.activity.ComponentActivity.startActivityForResult(ComponentActivity.java:574)
at android.app.Activity.startActivityForResult(Activity.java:4544)
at androidx.activity.ComponentActivity.startActivityForResult(ComponentActivity.java:560)
at android.app.Activity.startActivity(Activity.java:4905)
at android.app.Activity.startActivity(Activity.java:4873)
at c.bawp.securemessenger.ChooseActivity$1.onClick(ChooseActivity.java:26)
at android.view.View.performClick(View.java:6597)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25885)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
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)
2021-06-26 05:10:29.657 24952-24952/c.bawp.securemessenger I/Process: Sending signal. PID: 24952 SIG: 9
So I don't know if this is the reason why it keeps shutting down any time I tap the button chat. The button chat is created in an activity.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="c.bawp.securemessenger">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="#style/Theme.SecureMessenger">
<activity android:name=".MainActivity" />
<activity android:name=".Main2Activity" />
<activity android:name=".ChooseActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".FileExchangeActivity"></activity>
</application>
</manifest>
package c.bawp.securemessenger;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.textfield.TextInputLayout;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private TextView status;
private Button btnConnect;
private ListView listView;
private Dialog dialog;
private TextInputLayout inputLayout;
private MessageAdapter messageAdapter;
private ArrayAdapter<String> chatAdapter;
private ArrayList<String> chatMessages;
private BluetoothAdapter bluetoothAdapter;
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_OBJECT = 4;
public static final int MESSAGE_TOAST = 5;
public static final String DEVICE_OBJECT = "device_name";
private static final int REQUEST_ENABLE_BLUETOOTH = 1;
private ChatController chatController;
private BluetoothDevice connectingDevice;
private ArrayAdapter<String> discoveredDevicesAdapter;
private Encrypt encrypt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsByIds();
//check device support bluetooth or not
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available!", Toast.LENGTH_SHORT).show();
finish();
}
//show bluetooth devices dialog when click connect button
btnConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showPrinterPickDialog();
}
});
//set chat adapter
messageAdapter = new MessageAdapter(this);
listView.setAdapter(messageAdapter);
encrypt = new Encrypt();
}
private final Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case ChatController.STATE_CONNECTED:
setStatus("Connected to: " + connectingDevice.getName());
btnConnect.setVisibility(View.INVISIBLE);
break;
case ChatController.STATE_CONNECTING:
setStatus("Connecting...");
//btnConnect.setEnabled(false);
break;
case ChatController.STATE_LISTEN:
case ChatController.STATE_NONE:
setStatus("Not connected");
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(writeBuf);
writeMessage = encrypt.decrypt(writeMessage);
//check out
MemberData data1 = new MemberData("Me","#C62828");
c.bawp.securemessenger.Message message1 = new c.bawp.securemessenger.Message(writeMessage, data1, true);
messageAdapter.add(message1);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
readMessage = encrypt.decrypt(readMessage);
MemberData data2 = new MemberData(connectingDevice.getName(),"#C62828");
Log.d("Bug", "handleMessage: " + readMessage);
c.bawp.securemessenger.Message message2 = new c.bawp.securemessenger.Message(readMessage, data2, false);
messageAdapter.add(message2);
break;
case MESSAGE_DEVICE_OBJECT:
connectingDevice = msg.getData().getParcelable(DEVICE_OBJECT);
Toast.makeText(getApplicationContext(), "Connected to " + connectingDevice.getName(),
Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString("toast"),
Toast.LENGTH_SHORT).show();
break;
}
return false;
}
});
private void showPrinterPickDialog() {
dialog = new Dialog(this);
dialog.setContentView(R.layout.layout_bluetooth);
dialog.setTitle("Bluetooth Devices");
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
//Initializing bluetooth adapters
ArrayAdapter<String> pairedDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
discoveredDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
//locate listviews and attach the adapters
ListView listView = dialog.findViewById(R.id.pairedDeviceList);
ListView listView2 = dialog.findViewById(R.id.discoveredDeviceList);
listView.setAdapter(pairedDevicesAdapter);
listView2.setAdapter(discoveredDevicesAdapter);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(discoveryFinishReceiver, filter);
// Register for broadcasts when discovery has finished
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
pairedDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
pairedDevicesAdapter.add(getString(R.string.none_paired));
}
//Handling listview item click event
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
dialog.findViewById(R.id.cancelButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.setCancelable(true);
dialog.show();
}
private void setStatus(String s) {
status.setText(s);
}
private void connectToDevice(String deviceAddress) {
bluetoothAdapter.cancelDiscovery();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
chatController.connect(device);
}
private void findViewsByIds() {
status = findViewById(R.id.status);
btnConnect = findViewById(R.id.btn_connect);
listView = findViewById(R.id.list);
inputLayout = findViewById(R.id.input_layout);
Button btnSend = findViewById(R.id.btn_send);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Objects.requireNonNull(inputLayout.getEditText()).getText().toString().equals("")) {
Toast.makeText(MainActivity.this, "Please input some texts", Toast.LENGTH_SHORT).show();
} else {
//TODO: here
sendMessage(inputLayout.getEditText().getText().toString());
inputLayout.getEditText().setText("");
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BLUETOOTH) {
if (resultCode == Activity.RESULT_OK) {
chatController = new ChatController(this, handler);
} else {
Toast.makeText(this, "Bluetooth still disabled, turn off application!", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void sendMessage(String message) {
if (chatController.getState() != ChatController.STATE_CONNECTED) {
Toast.makeText(this, "Connection was lost!", Toast.LENGTH_SHORT).show();
return;
}
if (message.length() > 0) {
message = encrypt.encrypt(message);
byte[] send = message.getBytes();
chatController.write(send);
}
}
#Override
public void onStart() {
super.onStart();
if (!bluetoothAdapter.isEnabled()) {
Intent dIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
dIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3000);
startActivity(dIntent);
} else {
chatController = new ChatController(this, handler);
}
}
#Override
public void onResume() {
super.onResume();
if (chatController != null) {
if (chatController.getState() == ChatController.STATE_NONE) {
chatController.start();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (chatController != null)
chatController.stop();
}
private final BroadcastReceiver discoveryFinishReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
discoveredDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
discoveredDevicesAdapter.clear();
//setProgressBarIndeterminateVisibility(false);
// setSupportProgressBarIndeterminateVisibility(true);
setTitle("Select a device to connect");
if (discoveredDevicesAdapter.getCount() == 0) {
discoveredDevicesAdapter.add("No devices found");
}
} else {
discoveredDevicesAdapter.add("Scanning Bluetooth Devices....");
}
}
};
}

Encrypt Bluetooth Chat

Having issues with the app, shuts down any time I click on the chat button. I just submitted my manifest, gradle , xml, and the mainactivity to check what really went wrong. Thanks
I have an error from the logcat
GoldfishAddressSpaceHostMemoryAllocator: ioctl_ping failed for device_type=5, ret=-1.
So I don't know if this is the reason why it keeps shutting down any time I tap the button chat. The button chat is created in an activity.xml.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="c.bawp.securemessenger">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="#style/Theme.SecureMessenger">
<activity android:name=".MainActivity" />
<activity android:name=".Main2Activity" />
<activity android:name=".ChooseActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity android:name=".FileExchangeActivity"></activity>
</application>
</manifest>
package c.bawp.securemessenger;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.textfield.TextInputLayout;
import java.util.ArrayList;
import java.util.Objects;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private TextView status;
private Button btnConnect;
private ListView listView;
private Dialog dialog;
private TextInputLayout inputLayout;
private MessageAdapter messageAdapter;
private ArrayAdapter<String> chatAdapter;
private ArrayList<String> chatMessages;
private BluetoothAdapter bluetoothAdapter;
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_OBJECT = 4;
public static final int MESSAGE_TOAST = 5;
public static final String DEVICE_OBJECT = "device_name";
private static final int REQUEST_ENABLE_BLUETOOTH = 1;
private ChatController chatController;
private BluetoothDevice connectingDevice;
private ArrayAdapter<String> discoveredDevicesAdapter;
private Encrypt encrypt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsByIds();
//check device support bluetooth or not
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available!", Toast.LENGTH_SHORT).show();
finish();
}
//show bluetooth devices dialog when click connect button
btnConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showPrinterPickDialog();
}
});
//set chat adapter
messageAdapter = new MessageAdapter(this);
listView.setAdapter(messageAdapter);
encrypt = new Encrypt();
}
private final Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case ChatController.STATE_CONNECTED:
setStatus("Connected to: " + connectingDevice.getName());
btnConnect.setVisibility(View.INVISIBLE);
break;
case ChatController.STATE_CONNECTING:
setStatus("Connecting...");
//btnConnect.setEnabled(false);
break;
case ChatController.STATE_LISTEN:
case ChatController.STATE_NONE:
setStatus("Not connected");
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(writeBuf);
writeMessage = encrypt.decrypt(writeMessage);
//check out
MemberData data1 = new MemberData("Me","#C62828");
c.bawp.securemessenger.Message message1 = new c.bawp.securemessenger.Message(writeMessage, data1, true);
messageAdapter.add(message1);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
readMessage = encrypt.decrypt(readMessage);
MemberData data2 = new MemberData(connectingDevice.getName(),"#C62828");
Log.d("Bug", "handleMessage: " + readMessage);
c.bawp.securemessenger.Message message2 = new c.bawp.securemessenger.Message(readMessage, data2, false);
messageAdapter.add(message2);
break;
case MESSAGE_DEVICE_OBJECT:
connectingDevice = msg.getData().getParcelable(DEVICE_OBJECT);
Toast.makeText(getApplicationContext(), "Connected to " + connectingDevice.getName(),
Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString("toast"),
Toast.LENGTH_SHORT).show();
break;
}
return false;
}
});
private void showPrinterPickDialog() {
dialog = new Dialog(this);
dialog.setContentView(R.layout.layout_bluetooth);
dialog.setTitle("Bluetooth Devices");
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
//Initializing bluetooth adapters
ArrayAdapter<String> pairedDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
discoveredDevicesAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
//locate listviews and attach the adapters
ListView listView = dialog.findViewById(R.id.pairedDeviceList);
ListView listView2 = dialog.findViewById(R.id.discoveredDeviceList);
listView.setAdapter(pairedDevicesAdapter);
listView2.setAdapter(discoveredDevicesAdapter);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(discoveryFinishReceiver, filter);
// Register for broadcasts when discovery has finished
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
pairedDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
pairedDevicesAdapter.add(getString(R.string.none_paired));
}
//Handling listview item click event
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
bluetoothAdapter.cancelDiscovery();
String info = ((TextView) view).getText().toString();
String address = info.substring(info.length() - 17);
connectToDevice(address);
dialog.dismiss();
}
});
dialog.findViewById(R.id.cancelButton).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.setCancelable(true);
dialog.show();
}
private void setStatus(String s) {
status.setText(s);
}
private void connectToDevice(String deviceAddress) {
bluetoothAdapter.cancelDiscovery();
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
chatController.connect(device);
}
private void findViewsByIds() {
status = findViewById(R.id.status);
btnConnect = findViewById(R.id.btn_connect);
listView = findViewById(R.id.list);
inputLayout = findViewById(R.id.input_layout);
Button btnSend = findViewById(R.id.btn_send);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Objects.requireNonNull(inputLayout.getEditText()).getText().toString().equals("")) {
Toast.makeText(MainActivity.this, "Please input some texts", Toast.LENGTH_SHORT).show();
} else {
//TODO: here
sendMessage(inputLayout.getEditText().getText().toString());
inputLayout.getEditText().setText("");
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BLUETOOTH) {
if (resultCode == Activity.RESULT_OK) {
chatController = new ChatController(this, handler);
} else {
Toast.makeText(this, "Bluetooth still disabled, turn off application!", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void sendMessage(String message) {
if (chatController.getState() != ChatController.STATE_CONNECTED) {
Toast.makeText(this, "Connection was lost!", Toast.LENGTH_SHORT).show();
return;
}
if (message.length() > 0) {
message = encrypt.encrypt(message);
byte[] send = message.getBytes();
chatController.write(send);
}
}
#Override
public void onStart() {
super.onStart();
if (!bluetoothAdapter.isEnabled()) {
Intent dIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
dIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3000);
startActivity(dIntent);
} else {
chatController = new ChatController(this, handler);
}
}
#Override
public void onResume() {
super.onResume();
if (chatController != null) {
if (chatController.getState() == ChatController.STATE_NONE) {
chatController.start();
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (chatController != null)
chatController.stop();
}
private final BroadcastReceiver discoveryFinishReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
discoveredDevicesAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
discoveredDevicesAdapter.clear();
//setProgressBarIndeterminateVisibility(false);
// setSupportProgressBarIndeterminateVisibility(true);
setTitle("Select a device to connect");
if (discoveredDevicesAdapter.getCount() == 0) {
discoveredDevicesAdapter.add("No devices found");
}
} else {
discoveredDevicesAdapter.add("Scanning Bluetooth Devices....");
}
}
};
}

Resources