Bluetooth sending data - java

Im new at android development. I'm developing an app where first of all, I have a main activity where I must turn On/Off the bluetooth, make it discoverable, search devices and connect to them.
After this, I go to other activity where I have a text view with a edittext and a send button, where I can write something and send it.
I've got working all the bluetooth enabling/disabling stuff, but now I need to connect to new found devices and then enter to the chat type activity and send.
I now this is pretty much work, but it would be great if you can give me an example of how can I do this. This is the code i have:
public class BTActivity extends Activity {
// Intent request codes
private static final int REQUEST_DISCOVERABLE_BT = 0;
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
// Debugging
private static final String TAG = "BluetoothChat";
private static final boolean D = true;
// Name of the connected device
public static String mConnectedDeviceName = null;
// Array adapter for device list
private ArrayAdapter<String> mArrayAdapter;
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button1 = (Button) findViewById(R.id.boton1);
final Button button2 = (Button) findViewById(R.id.boton2);
final Button button3 = (Button) findViewById(R.id.boton3);
final Button button4 = (Button) findViewById(R.id.boton4);
final Button button5 = (Button) findViewById(R.id.boton5);
button5.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
lanzarComunicacion (null);
}
});
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
});
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//LLAMA A LA DIALOG ACTIVITY PARA VISUALIZAR LOS DISPOSITIVOS
LanzarBusqueda(null);
}
});
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!mBluetoothAdapter.isDiscovering()) {
Context context = getApplicationContext();
CharSequence text = "MAKING YOUR DEVICE DISCOVERABLE";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
});
button4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mBluetoothAdapter.disable();
Context context = getApplicationContext();
CharSequence text = "TURNING_OFF BLUETOOTH";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, 15);
toast.show();
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
connectDevice(data);
}
}
}
private void connectDevice(Intent data) {
String address = data.getExtras().getString(DeviceListDialog.EXTRA_DEVICE_ADDRESS);
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
BTCommunication.mChatService.connect(device);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.bt, menu);
return true;
}
public void lanzarComunicacion (View view) {
Intent i = new Intent(this, BTCommunication.class);
startActivity(i);
}
public void LanzarBusqueda (View view) {
Intent i = new Intent(this, DeviceListDialog.class);
startActivity(i);
}
}

Related

How to store the login state in sharedpreferences

I'm making an Android app and in my app, I add the feature of storing the login state.
My Splash screen:
public class Splash extends AppCompatActivity {
private SharedPreferences preferences;
public int a = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressbar);
new CountDownTimer(5000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
a = a + 1;
progressBar.setProgress(a);
}
#Override
public void onFinish() {
SharedPreferences preferences = getSharedPreferences("login", MODE_PRIVATE);
String check = preferences.getString("login", "off");
if (check.equals("on")) {
startActivity(new Intent(Splash.this, Menu.class));
} else {
startActivity(new Intent(Splash.this, LoginPage.class));
}
}
}.start();
} }
My Login screen:
public class LoginPage extends AppCompatActivity {
private SharedPreferences preferences;
Context context;
Button login, register, database;
EditText username;
EditText password;
TextView msg;
MyDBManager db;
static final int REGISTRATION_REQUEST = 1; // The request code
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginpage);
db = new MyDBManager(this);
msg = (TextView) findViewById(R.id.msg);
login = (Button) findViewById(R.id.button);
register = (Button) findViewById(R.id.button2);
database = (Button) findViewById(R.id.button3);
username = (EditText) findViewById(R.id.user);
password = (EditText) findViewById(R.id.pass);
// Click and move to the next activity
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
db.open();
Cursor c = db.getUser(username.getText().toString(), password.getText().toString());
if (c.moveToFirst()) {
db.close();
context.startActivity(new Intent(context,Menu.class));
// Intent i=new Intent(getApplicationContext(),Menu.class); //
i.putExtra("Username", username.getText().toString()); //
startActivity(i); // call Login Activity
Store();
}
else
{
db.close();
// set error message when the username and/or password is not valid
msg.setText("Unable to login: wrong username or password!");
// Stay at the current activity.
}
}
private void Store() {
SharedPreferences preferences=context.getSharedPreferences("login",Context.MODE_PRIVATE);
SharedPreferences.Editor editor=preferences.edit();
editor.putString("login_status","on");
editor.commit();
}
});
// Click and move to the next activity
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginPage.this, Registration.class);
startActivityForResult(intent, REGISTRATION_REQUEST);
}
});
// Click and move to the next activity
database.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginPage.this, Database.class);
startActivity(intent);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REGISTRATION_REQUEST) {
//if(resultCode == Registration.RESULT_OK){
Log.d("Pikatchu", "User successfully registered!");
Bundle res = data.getExtras();
String result = res.getString("result");
System.out.println(result);
msg.setText(result);
}
}
}
My Menu screen:
public class Menu extends AppCompatActivity {
private SharedPreferences preferences;
Button startJourney, displayJourneys;
TextView msg; // where to display the name of the user
Button buttonLogout ;
/* the string is where to store data when we select something */
String db_username;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
buttonLogout = (Button) findViewById(R.id.btn_logout);
msg = (TextView) findViewById(R.id.msg);
startJourney = (Button) findViewById(R.id.recordingmode);
// Bundle bundle = getIntent().getExtras(); //
db_username = (bundle.getString("Username")); //// //// // Set
Welcome message to the user who logged in //
msg.setText("Welcome "+db_username);
// Click and move to the next activity // startJourney.setOnClickListener(new View.OnClickListener() { //
#Override // public void onClick(View v) { //
Intent intent = new Intent(Menu.this, Recordingmode.class); //
intent.putExtra("Username", db_username); //
startActivity(intent); // } // });
// Click and move to the next activity buttonLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences preferences=getSharedPreferences("login", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=preferences.edit();
editor.putString("login_status","off");
editor.commit();
finish();
moveTaskToBack(true);
} });
}
}
But if I login in the app, the error is thrown:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null
object reference

Activity intent not working on button click

Hello Stackoverflow community!
Recently, a strange error occured to me. It is with a button in my app. When i press it there is nothing happening. No errors, or crashes but also Intent is not functioning. The transition to DeleteAccountActivity is not happening. I don't know why is this happening. The intent which I am using is very simple(passes nothing). Please help me
AccountSettingsActivity.java
public class AccountSettingsActivity extends AppCompatActivity {
private static final String TAG = "AccountSettingsActivity";
private static final int ACTIVITY_NUM = 4;
private String user_id;
private Context mContext;
public SectionsStatePagerAdapter pagerAdapter;
private ViewPager mViewPager;
private RelativeLayout mRelativeLayout;
private Button mDelete;
User mUser;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accountsettings);
mContext = AccountSettingsActivity.this;
Log.d(TAG, "onCreate: started.");
mViewPager = (ViewPager) findViewById(R.id.viewpager_container);
mRelativeLayout = (RelativeLayout) findViewById(R.id.relLayout1);
mDelete = (Button) findViewById(R.id.btnDelete);
User mUser = new User();
setupSettingsList();
setupBottomNavigationView();
setupFragments();
getIncomingIntent();
//setup the backarrow for navigating back to "ProfileActivity"
ImageView backArrow = (ImageView) findViewById(R.id.backArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
}
});
}
});
}
private void deleteAccounts(){
/* DatabaseReference deleteUser = FirebaseDatabase.getInstance().getReference("users").child(user_id);
DatabaseReference deleteUserPhotos = FirebaseDatabase.getInstance().getReference("user_photos").child(user_id);
DatabaseReference deleteUserPhotoComments = FirebaseDatabase.getInstance().getReference("comments").child(user_id);
deleteUser.removeValue();
deleteUserPhotos.removeValue();
deleteUserPhotoComments.removeValue();*/
// getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.dbname_users))
// .child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(mUser.getUser_id())
.removeValue();
/* FirebaseDatabase.getInstance().getReference()
.child(getString(R.string.dbname_followers))
.child(mUser.getUser_id())
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.removeValue(); */
}
private void getIncomingIntent(){
Intent intent = getIntent();
if(intent.hasExtra(getString(R.string.selected_image))
|| intent.hasExtra(getString(R.string.selected_bitmap))){
//if there is an imageUrl attached as an extra, then it was chosen from the gallery/photo fragment
Log.d(TAG, "getIncomingIntent: New incoming imgUrl");
if(intent.getStringExtra(getString(R.string.return_to_fragment)).equals(getString(R.string.edit_profile_fragment))){
if(intent.hasExtra(getString(R.string.selected_image))){
//set the new profile picture
FirebaseMethods firebaseMethods = new FirebaseMethods(AccountSettingsActivity.this);
firebaseMethods.uploadNewPhoto(getString(R.string.profile_photo), null, 0,
intent.getStringExtra(getString(R.string.selected_image)), null);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
//set the new profile picture
FirebaseMethods firebaseMethods = new FirebaseMethods(AccountSettingsActivity.this);
firebaseMethods.uploadNewPhoto(getString(R.string.profile_photo), null, 0,
null,(Bitmap) intent.getParcelableExtra(getString(R.string.selected_bitmap)));
}
}
}
if(intent.hasExtra(getString(R.string.calling_activity))){
Log.d(TAG, "getIncomingIntent: received incoming intent from " + getString(R.string.profile_activity));
setViewPager(pagerAdapter.getFragmentNumber(getString(R.string.edit_profile_fragment)));
}
}
private void setupFragments(){
pagerAdapter = new SectionsStatePagerAdapter(getSupportFragmentManager());
pagerAdapter.addFragment(new EditProfileFragment(), getString(R.string.edit_profile_fragment)); //fragment 0
pagerAdapter.addFragment(new SignOutFragment(), getString(R.string.sign_out_fragment)); //fragment 1
// pagerAdapter.addFragment(new DeleteAccountFragment(), "Delete Account");
}
public void setViewPager(int fragmentNumber){
mRelativeLayout.setVisibility(View.GONE);
Log.d(TAG, "setViewPager: navigating to fragment #: " + fragmentNumber);
mViewPager.setAdapter(pagerAdapter);
mViewPager.setCurrentItem(fragmentNumber);
}
private void setupSettingsList(){
Log.d(TAG, "setupSettingsList: initializing 'Account Settings' list.");
ListView listView = (ListView) findViewById(R.id.lvAccountSettings);
ArrayList<String> options = new ArrayList<>();
options.add(getString(R.string.edit_profile_fragment)); //fragment 0
options.add(getString(R.string.sign_out_fragment)); //fragement 1
// options.add("Delete Account");
ArrayAdapter adapter = new ArrayAdapter(mContext, android.R.layout.simple_list_item_1, options);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: navigating to fragment#: " + position);
setViewPager(position);
}
});
}
/**
* BottomNavigationView setup
*/
private void setupBottomNavigationView(){
Log.d(TAG, "setupBottomNavigationView: setting up BottomNavigationView");
BottomNavigationViewEx bottomNavigationViewEx = (BottomNavigationViewEx) findViewById(R.id.bottomNavViewBar);
BottomNavigationViewHelper.setupBottomNavigationView(bottomNavigationViewEx);
BottomNavigationViewHelper.enableNavigation(mContext, this,bottomNavigationViewEx);
Menu menu = bottomNavigationViewEx.getMenu();
MenuItem menuItem = menu.getItem(ACTIVITY_NUM);
menuItem.setChecked(true);
}
}
DeleteAccountActivity.java
public class DeleteAccountActivity extends AppCompatActivity {
Button yesButton;
Button cancelButton;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_delete_account);
yesButton = (Button) findViewById(R.id.btnDelete2);
cancelButton = (Button) findViewById(R.id.btnDelete3);
yesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
deleteAllData();
Intent intent = new Intent(mContext, RegisterActivity.class);
startActivity(intent);
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(mContext, AccountSettingsActivity.class);
}
});
}
public void deleteAllData(){
DatabaseReference deleteUser = FirebaseDatabase.getInstance().getReference()
.child("users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
DatabaseReference deleteUserPhotos = FirebaseDatabase.getInstance().getReference()
.child("user_photos")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
DatabaseReference deleteUserPhotoComments = FirebaseDatabase.getInstance().getReference()
.child("user_account_settings")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
DatabaseReference deleteUserFollowing = FirebaseDatabase.getInstance().getReference()
.child("following")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
DatabaseReference deleteUserFollowers = FirebaseDatabase.getInstance().getReference()
.child("followers")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
deleteUser.removeValue();
deleteUserPhotos.removeValue();
deleteUserPhotoComments.removeValue();
deleteUserFollowing.removeValue();
deleteUserFollowers.removeValue();
}
}
Issue :
Press backarrow (But this will finish the activity)
Press mdelete to trigger the intent. (so no way to trigger intent)
Because when you press backarrow, you are setting the listener on mdelete which actually has the code to trigger intent and finish will kill the activity so no way to trigger intent
Solution : Separate the listeners
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
}
});
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
}
});
Please, change the lines with setting the clickListeners to this:
ImageView backArrow = (ImageView) findViewById(R.id.backArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
}
});
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
}
});
I think your onCreate() method should look like this:
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accountsettings);
mContext = AccountSettingsActivity.this;
Log.d(TAG, "onCreate: started.");
mViewPager = (ViewPager) findViewById(R.id.viewpager_container);
mRelativeLayout = (RelativeLayout) findViewById(R.id.relLayout1);
mDelete = (Button) findViewById(R.id.btnDelete);
User mUser = new User();
setupSettingsList();
setupBottomNavigationView();
setupFragments();
getIncomingIntent();
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
}
});
//setup the backarrow for navigating back to "ProfileActivity"
ImageView backArrow = (ImageView) findViewById(R.id.backArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
}
});
}
One simple thing i can see by skimming through is that the onClick listener for your button that should take you to delete activity is assigned inside the back arrow onClick listener.
So the only time your delete button is assigned a click listener is when you press the back button, and it wont still assign because you already called
finish();
On the activity
Change
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
} });
} });
To
backArrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to 'ProfileActivity'");
finish();
} });
mDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, DeleteAccountActivity.class);
startActivity(intent);
} });
Hope this helps.

Android studio pass ListView to another activity

I am trying to pass an array list to another activity but it seems that is not enough. I searched all day to pass the array list with "intent" but with no success. I wrote a code for learning purposes. How to pass the data and show the Arraylist in a second activity?
The action button is btn_save. If you want further details let me know.
The code is in
MainActivity (first activity):
public class MainActivity extends AppCompatActivity {
ArrayList<String> addArray = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText editTextOne = (EditText) findViewById(R.id.editTextOne);
final EditText editTextTwo = (EditText) findViewById(R.id.editTextTwo);
Button btn_showText = (Button) findViewById(R.id.buttonShow);
final TextView textView = (TextView) findViewById(R.id.textResults);
Button btn_refresh = (Button) findViewById(R.id.btn_refresh);
Button btn_close = (Button) findViewById(R.id.btn_close);
Button btn_save = (Button) findViewById(R.id.btn_save);
final ListView showMe = (ListView) findViewById(R.id.list_items);
btn_showText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = editTextOne.getText().toString();
String textTwo = editTextTwo.getText().toString();
if (text.length() == 0 || textTwo.length() == 0){
textView.setText("You must enter Name & Surname");
}else {
textView.setText(Html.fromHtml(
"<font color=\"red\">"+ text + "</font> " +
"<font color=\"blue\"><b>" + textTwo + " </b></font>"));
}
}
});
btn_refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
startActivity(getIntent());
}
});
btn_close.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
System.exit(0);
}
});
btn_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Context context = getApplicationContext();
// CharSequence mytext = "Hahahaha";
// int duration = Toast.LENGTH_SHORT;
// Toast toast = Toast.makeText(context,mytext,duration);
// toast.show();
String text = editTextOne.getText().toString();
String textTwo = editTextTwo.getText().toString();
String getInput = text + textTwo;
if (addArray.contains(getInput)){
Toast.makeText(getBaseContext(), "Item already Added!", Toast.LENGTH_LONG).show();
}
else if (getInput == null || getInput.trim().equals("")){
Toast.makeText(getBaseContext(), "Input field is empty", Toast.LENGTH_LONG).show();
}
else{
addArray.add(getInput);
ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);
showMe.setAdapter(adapter);
Intent intent = new Intent(MainActivity.this, ListOfNames.class);
((EditText)findViewById(R.id.editTextOne)).setText(" ");
((EditText)findViewById(R.id.editTextTwo)).setText(" ");
}
}
});
}
public void onButtonClick(View v){
if (v.getId() == R.id.btn_list){
Intent i = new Intent(MainActivity.this, ListOfNames.class);
startActivity(i);
}
}
}
ListOfNames second activity: (almost empty)
public class ListOfNames extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_screen);
}
}
If you are trying to pass a arraylist of string then it will be easy. Just pass arraylist with intent like this:
ArrayList<String> list = new ArrayList<String>();
Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);
intent.putStringArrayListExtra("key", list);
startActivity(intent);
And receive it in ActivityTwo like this:
ArrayList<String> list = getIntent().getStringArrayListExtra("key");
I found a temporary solution for this (The app is not broke). The only problem is the arraylist didn't increased. It contains and show only the last value.
Main Activity:
...
else{
// addArray.add(getInput);
// ArrayAdapter<String> adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, addArray);
// showMe.setAdapter(adapter);
Intent intent = new Intent(MainActivity.this, ListOfNames.class);
intent.putExtra("data", getInput);
startActivity(intent);
// ((EditText)findViewById(R.id.editTextOne)).setText(" ");
// ((EditText)findViewById(R.id.editTextTwo)).setText(" ");
}
...
ListOfNames (Second Activity):
public class ListOfNames extends Activity {
ArrayList<String> addArrayT = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_screen);
Bundle bundle = getIntent().getExtras();
String data = bundle.getString("data");
Button btn_more = (Button) findViewById(R.id.btn_more);
ListView showMe = (ListView) findViewById(R.id.list_items);
addArrayT.add(data);
ArrayAdapter<String> adapterT = new ArrayAdapter<>(ListOfNames.this, android.R.layout.simple_list_item_1, addArrayT);
showMe.setAdapter(adapterT);
}
public void onClickMore(View v){
if (v.getId() == R.id.btn_more){
Intent i = new Intent(ListOfNames.this, MainActivity.class);
startActivity(i);
}
}
}

Activity does not even call onActivityResult

I know,I have seen the duplicates. But none of them solved my issue.
I want my code to get newMessage from EditMessage activity and pass it to the SendMessage Activity, and I know I may not need to use onActivityResult tough I still want to learn what's the issue here.
I'have added log messages to check where my problem is but it doesn't even run my Log inside the onActivityResult.
Here's the code:
EditMessageActivity:
public static final String MESSAGE = "message";
EditText currentTextEditText;
Button sendButton;
Button saveButton;
Button cancelButton;
Button concatenateButton;
private String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_message_layout);
message = getIntent().getStringExtra(SendMessageActivity.MESSAGE);
currentTextEditText = (EditText) findViewById(R.id.currentText_EditText);
sendButton = (Button) findViewById(R.id.sendButton);
saveButton = (Button) findViewById(R.id.saveButton);
cancelButton = (Button) findViewById(R.id.cancelButton);
concatenateButton = (Button) findViewById(R.id.concatenateButton);
if (message != null) //Activity may be started via "edit" Button
currentTextEditText.setText(message);
currentTextEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
message = currentTextEditText.getText().toString();
}
#Override
public void afterTextChanged(Editable s) {
message = currentTextEditText.getText().toString();
}
});
concatenateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String[] messages = getResources().getStringArray(R.array.messages_array);
AlertDialog.Builder builder = new AlertDialog.Builder(EditMessage.this);
builder.setTitle("Sonuna Ekle").setItems(messages, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
char lastChar = message.charAt(message.length() - 1);
String messageToAdd = messages[which];
if (lastChar == '!' || lastChar == '?' || lastChar == '.') {
message += " " + messageToAdd;
} else {
message += " " + messageToAdd.toLowerCase();
}
currentTextEditText.setText(message);
dialog.cancel();
}
});
builder.setCancelable(true);
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(EditMessage.this, NumberSelectActivity.class);
intent.putExtra(MESSAGE, message);
startActivity(intent);
finish();
}
});
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Custom", "Save buttn clicked");
Intent intent = new Intent(EditMessage.this, SendMessageActivity.class);
intent.putExtra(MESSAGE, message);
setResult(RESULT_OK);
startActivityForResult(intent, SendMessageActivity.REQUEST_NEW_MESSAGE);
finish();
Log.i("Custom", "Custom Message created :" + message);
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
SendMessageActivity:
public static final String MESSAGE = "message";
public static final int REQUEST_NEW_MESSAGE = 1001;
private static String message;
ListView messageListView;
Button createMessage;
ArrayList<String> messageList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_message);
//Retrive Pre-Defined Messages
//TODO Add in-app message defining
String[] dbMessages = getResources().getStringArray(R.array.messages_array);
for (int i = 0; i < dbMessages.length; i++) {
messageList.add(dbMessages[i]);
}
//Create the array adapter
//TODO Upgrade this to a custom adapter which will also show an small image related to the message
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, messageList);
createMessage = (Button) findViewById(R.id.createMessageBtn);
createMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startEditMessage("");
}
});
messageListView = (ListView) findViewById(R.id.messagesListView);
messageListView.setAdapter(adapter);
//Make this one clickable
messageListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
message = messageList.get(position);
AlertDialog.Builder builder = new AlertDialog.Builder(SendMessageActivity.this);
builder.setTitle("Send Message");
builder.setMessage(message);
builder.setPositiveButton("Gönder", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(SendMessageActivity.this, NumberSelectActivity.class);
intent.putExtra(MESSAGE, message);
startActivity(intent);
}
});
builder.setNeutralButton("Düzenle", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//TODO Create new activity to edit message and send it or just cancel it
//Todo and return back
startEditMessage(message);
}
});
builder.setNegativeButton("İptal", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.setCancelable(true);
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.i("Custom", "Result OK değil :" + message);
if (resultCode == RESULT_OK) {
Log.i("Custom","Result OK:" + message);
if (requestCode == REQUEST_NEW_MESSAGE) {
Log.i("Custom","request is ok :" + message);
String newMessage = getIntent().getStringExtra(EditMessage.MESSAGE);
if (newMessage != null) {
Log.i("Custom","Message is not null :" + message);
messageList.add(newMessage);
//TODO Create new method to load all messages from database and just call that method
ArrayAdapter<String> updatedAdapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, messageList);
messageListView.setAdapter(updatedAdapter);
Log.i("Custom", "Updated adapter :" + message);
}
}
}
}
public void startEditMessage(String message) {
Intent intent = new Intent(SendMessageActivity.this, EditMessage.class);
intent.putExtra(MESSAGE, message);
startActivity(intent);
}
Any help will be appriciated.Thanks.
I want my code to get newMessage from EditMessage activity and pass it
to the SendMessage Activity.
Lets say there are three activities A(MainActivity), B(EditMessageActivity), C(SendMessageActivity).
To get message from B to A, you startActivityForResult() from A. When required value is retreived in B, you setResult() in B and then call finish().
The result will be received in A by overriding onActivityResult(). And then start C, and put the value in intent.
For example, reporting value back to MainActivity from EditMessageActivity:
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Custom", "Save buttn clicked");
Intent intent = new Intent();
intent.putExtra(MESSAGE, message);
setResult(RESULT_OK, intent);
finish();
Log.i("Custom", "Custom Message created :" + message);
}
});
If there are only two activities, then no need of onActivityResult(). You can directly pass the message to SendMessageActivity using Intent.
For example, sending value from MainActivity to EditMessageActivity without onActivityResult():
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Custom", "Save buttn clicked");
Intent intent = new Intent(EditMessageActivity.this, SendMessageActivity.class);
intent.putExtra(MESSAGE, message);
startActivity(intent);
Log.i("Custom", "Custom Message created :" + message);
}
});
Use
int request = 0;// Any number to identify your request
startActivityForResult(intent,request);
Instead of
startActivity(intent);
And don't use
finish()
;// function from the calling activity which will remove the activity from the stack.

Android: button does not work

So there is 4 buttons on this page... 3 of them work fine, the 4th button, which links to ToolsTableLayout.class does not respond at all. There are no erros, the app does not crash or anything... you just click the button and nothing happens.
Code for the button class:
public class MainMenu extends Activity implements OnClickListener{
private String result;
boolean isScanout;
public static final String SCAN_RESULT = "MyPreferencesFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
Button ScanOut=(Button)findViewById(R.id.scanout);
ScanOut.setOnClickListener(this);
Button ScanIn=(Button)findViewById(R.id.scanin);
ScanIn.setOnClickListener(this);
Button EndSession = (Button) findViewById(R.id.endsession);
EndSession.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.scanout){
isScanout = true;
IntentIntegrator.initiateScan(this);
}
else if(v.getId()==R.id.scanin){
isScanout = false;
IntentIntegrator.initiateScan(this);
}
else if(v.getId()==R.id.endsession){
Intent endsessionintent = new Intent(MainMenu.this, MainActivity.class);
startActivity(endsessionintent);
}
else if(v.getId()==R.id.toolDB){
Intent i = new Intent(MainMenu.this, ToolsTableLayout.class);
startActivity(i);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case IntentIntegrator.REQUEST_CODE: {
if (resultCode != RESULT_CANCELED) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (scanResult != null) {
String qrCode = scanResult.getContents();
SharedPreferences codeHack = getSharedPreferences(SCAN_RESULT,0);
SharedPreferences.Editor editor = codeHack.edit();
editor.putString("entry", qrCode);
editor.commit();
}
}
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
R.id.toolDB is the button that makes no response..
and here is the ToolsTableLayout.java class (which does not open):
public class ToolsTableLayout extends Activity {
public static final String SCAN_RESULT = "MyPreferencesFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tablelayout2);
SharedPreferences codeHack = getSharedPreferences(SCAN_RESULT,0);
String QRcode = codeHack.getString("entry", "unregistered");
StringTokenizer token = new StringTokenizer(QRcode," ");
String name = token.nextToken();
String quantity = token.nextToken();
TextView t1 = (TextView) findViewById(R.id.slot1b);
TextView t2 = (TextView) findViewById(R.id.slot2b);
TextView t3 = (TextView) findViewById(R.id.slot3b);
ToolDB info = new ToolDB(this);
info.open();
String c1 = info.getRowID();
info.createEntry(name, quantity);
info.close();
t1.setGravity(Gravity.CENTER_HORIZONTAL);
t2.setGravity(Gravity.CENTER_HORIZONTAL);
t3.setGravity(Gravity.CENTER_HORIZONTAL);
t1.setText(c1);
t2.setText(name);
t3.setText(quantity);
}
}
not sure if the XML files are needed? if so let me know and I will update.
You did not set onClickListener for 4th button. Please add
Button btnToolDb = (Button) findViewById(R.id.toolDB);
btnToolDb.setOnClickListener(this);
Judging by the code you have provided, I believe you have forgotten to create and attach the ClickListener to the fourth button which is missing from the code.

Categories