I'm making a bluetooth application using android studio and the problem is that the application scans for devices once only. After it finds a device, it stops looking for other.I want to search for all available devices around my device. The activity code is:
package com.example.yubrajsharma.my_application;
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.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import java.util.ArrayList;
import static android.view.View.INVISIBLE;
public class MainActivity extends AppCompatActivity{
BluetoothAdapter mBluetoothAdapter;
int count;
Button lister;
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
String[] mBTDevice;
ArrayAdapter<String> adapter;
private static final String TAG = "MainActivity";
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);
}
}
};
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
unregisterReceiver(mReciever);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProgressBar pg = (ProgressBar) findViewById(R.id.progressBar);
pg.setVisibility(View.INVISIBLE);
Button searchbtn = (Button) findViewById(R.id.searchbtn);
Button lister = (Button) findViewById(R.id.lists);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter.isEnabled()){
lister.setVisibility(View.VISIBLE);
}
lister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listdata();
}
});
}
private BroadcastReceiver mReciever = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
ProgressBar pg = (ProgressBar) findViewById(R.id.progressBar);
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mBTDevices.add(device);
}
count = mBTDevices.size();
int j = 0;
mBTDevice = new String[count];
if(count>0) {
for (BluetoothDevice device : mBTDevices) {
mBTDevice[j] = device.getName();
j++;
}
ListView pairing = (ListView) findViewById(R.id.paired);
adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,mBTDevice);
pairing.setAdapter(adapter);
}
else{
mBTDevice[0] = "no devices found";
ListView pairing = (ListView) findViewById(R.id.paired);
adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,mBTDevice);
pairing.setAdapter(adapter);
}
mBluetoothAdapter.cancelDiscovery();
pg.setVisibility(View.INVISIBLE);
Log.d(TAG, "Disabled");
}
};
private void listdata() {
if(mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
mBluetoothAdapter.startDiscovery();
ProgressBar pg = (ProgressBar) findViewById(R.id.progressBar);
pg.setVisibility(View.VISIBLE);
IntentFilter infill = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReciever, infill);
}
public void enableDisableBT(View view) {
Button lister = (Button) findViewById(R.id.lists);
if(!mBluetoothAdapter.isEnabled()){
Intent enableBTintent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBTintent);
IntentFilter btIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, btIntent);
}
if(mBluetoothAdapter.isEnabled()){
mBluetoothAdapter.disable();
IntentFilter btIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, btIntent);
}
}
}
The Code for the xml file is:
<?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:layout_height="match_parent"
tools:context="com.example.yubrajsharma.my_application.MainActivity"
tools:layout_editor_absoluteY="81dp"
tools:layout_editor_absoluteX="0dp">
<Button
android:id="#+id/lists"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List Devices"
android:visibility="invisible"
app:layout_constraintLeft_toRightOf="#+id/searchbtn"
app:layout_constraintBottom_toBottomOf="#+id/searchbtn"
android:layout_marginRight="28dp"
android:layout_marginEnd="28dp"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/paired"
android:layout_alignEnd="#+id/paired" />
<Button
android:id="#+id/searchbtn"
android:onClick="enableDisableBT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ON/OFF"
android:visibility="visible"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="3dp" />
<ListView
android:id="#+id/paired"
android:layout_width="368dp"
android:layout_height="422dp"
app:layout_constraintTop_toBottomOf="#+id/lists"
app:layout_constraintLeft_toLeftOf="#+id/searchbtn"
android:layout_marginBottom="13dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginEnd="29dp"
android:layout_marginRight="29dp"
android:layout_toLeftOf="#+id/lists"
android:layout_toStartOf="#+id/lists"
tools:visibility="invisible" />
</RelativeLayout>
How to scan all the available devices?
Well in your BroadcastReceiver.onReceive method once it gets called you call:
mBluetoothAdapter.cancelDiscovery();
So this stops the discovering process. Try to remove this line and see what happens.
However keep in mind the following from the official documentation:
Because discovery is a heavyweight procedure for the Bluetooth
adapter, this method should always be called before attempting to
connect to a remote device with connect(). Discovery is not managed by
the Activity, but is run as a system service, so an application should
always call cancel discovery even if it did not directly request a
discovery, just to be sure.
Related
I am trying to populate a listView with paired bluetooth devices. I tried doing so with a ListView in my MainActivity and it worked perfectly. However, when I tried it with a ListView in a different activity it crashed the app. I basically want to populate a ListView in a pop-up dialog box.
Here is the code:
activity_device_list.xml (MainActivity)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1">
<ListView
android:id="#+id/listDevicesMain"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
device_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.12"
android:gravity="center"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:text="Paired Devices"
android:textSize="25sp" />
<ListView
android:id="#+id/listDevicesDialog"
android:layout_width="match_parent"
android:layout_height="395dp"
android:layout_weight="0.38" />
</LinearLayout>
DeviceList.java
package example.btmodule;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
import static example.btmodule.R.layout.activity_device_list;
public class DeviceList extends AppCompatActivity {
ListView devicelist;
private BluetoothAdapter myBluetooth = null;
private Set<BluetoothDevice> pairedDevices;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_device_list);
myBluetooth = BluetoothAdapter.getDefaultAdapter();
if(myBluetooth == null)
{
//Show a mensag. that thedevice has no bluetooth adapter
Toast.makeText(getApplicationContext(), R.string.bluetooth_unavailable, Toast.LENGTH_LONG).show();
//finish apk
finish();
}
else {
if (myBluetooth.isEnabled()) {
} else {
//Ask to the user turn the bluetooth on
Intent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnBTon, 1);
}
}
}
private void pairedDevicesList()
{
pairedDevices = myBluetooth.getBondedDevices();
ArrayList list = new ArrayList();
devicelist = (ListView)findViewById(R.id.listDevicesDialog);
if (pairedDevices.size()>0)
{
for(BluetoothDevice bt : pairedDevices)
{
list.add(bt.getName() + "\n" + bt.getAddress()); //Get the device's name and the address
}
}
else
{
Toast.makeText(getApplicationContext(), R.string.no_devices_found, Toast.LENGTH_LONG).show();
}
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
devicelist.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
// menu item selection
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_connect:
showDialog();
pairedDevicesList();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// show the dialog for connected devices
private void showDialog(){
AlertDialog.Builder mBuilder = new AlertDialog.Builder(DeviceList.this);
View mView = getLayoutInflater().inflate(R.layout.device_dialog, null);
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
}
}
If I change devicelist to R.id.listDevicesMain the code works perfectly fine.
you calling the wrong list view the id of the list view as you have given is
<ListView
android:id="#+id/listDevicesMain"
android:layout_width="match_parent"
android:layout_height="match_parent" />
and you are trying to call the listview with id
devicelist = (ListView)findViewById(R.id.listDevicesDialog);
hope this will solve the issue.
devicelist = (ListView)findViewById(R.id.listDevicesDialog); - here you are looking for listDevicesDialog in activity layout, so devicesList becomes null. You should add devicelist = (ListView) mView.findViewById(R.id.listDevicesDialog); to showDialog() method and bring there rest of the operations related with searching for paired devices and setting adapter.
You can also call pairedDevicesList from showDialog and pass view where listDevicesDialog is:
private void pairedDevicesList(View dialogView)
{
pairedDevices = myBluetooth.getBondedDevices();
ArrayList list = new ArrayList();
devicelist = (ListView) dialogView.findViewById(R.id.listDevicesDialog);
...
}
// show the dialog for connected devices
private void showDialog()
{
AlertDialog.Builder mBuilder = new AlertDialog.Builder(DeviceList.this);
View mView = getLayoutInflater().inflate(R.layout.device_dialog, null);
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
pairedDevicesList(mView);
}
When i click on a button with ID "btnDiscoverable_on_off" and "lvNewDevices" i get this error :
java.lang.IllegalStateException: Could not find method btnDiscover(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'btnFindUnpairedDevices'
This is the code :
import android.Manifest;
import android.app.Fragment;
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.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class PrimoFragment extends Fragment implements
AdapterView.OnItemClickListener {
View myView;
private static final String TAG = "MainActivity";
BluetoothAdapter mBluetoothAdapter;
Button btnEnableDisable_Discoverable;
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
public DeviceListAdapter mDeviceListAdapter;
ListView lvNewDevices;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.primo_layout, container, false);
Button btnONOFF = (Button) myView.findViewById(R.id.btnONOFF);
btnEnableDisable_Discoverable = (Button) myView.findViewById(R.id.btnDiscoverable_on_off);
lvNewDevices = (ListView) myView.findViewById(R.id.lvNewDevices);
mBTDevices = new ArrayList<>();
//Broadcasts when bond state changes (ie:pairing)
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
getActivity().registerReceiver(mBroadcastReceiver4, filter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
lvNewDevices.setOnItemClickListener(PrimoFragment.this);
btnONOFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: enabling/disabling bluetooth.");
enableDisableBT();
}
});
return myView;
}
public void enableDisableBT(){
if(mBluetoothAdapter == null){
Log.d(TAG, "enableDisableBT: Does not have BT capabilities.");
}
if(!mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: enabling BT.");
Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBTIntent);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
getActivity().registerReceiver(mBroadcastReceiver1, BTIntent);
}
if(mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: disabling BT.");
mBluetoothAdapter.disable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
getActivity().registerReceiver(mBroadcastReceiver1, BTIntent);
}
}
public void btnEnableDisable_Discoverable(View view) {
Log.d(TAG, "btnEnableDisable_Discoverable: Making device discoverable for 300 seconds.");
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
IntentFilter intentFilter = new IntentFilter(mBluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
getActivity().registerReceiver(mBroadcastReceiver2,intentFilter);
}
public void btnDiscover(View view) {
Log.d(TAG, "btnDiscover: Looking for unpaired devices.");
if(mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "btnDiscover: Canceling discovery.");
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
getActivity().registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
if(!mBluetoothAdapter.isDiscovering()){
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
getActivity().registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
}
/**
* This method is required for all devices running API23+
* Android must programmatically check the permissions for bluetooth. Putting the proper permissions
* in the manifest is not enough.
*
* NOTE: This will only execute on versions > LOLLIPOP because it is not needed otherwise.
*/
private void checkBTPermissions() {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
int permissionCheck = this.getActivity().checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += this.getActivity().checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0) {
this.getActivity().requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
}
}else{
Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
}
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//first cancel discovery because its very memory intensive.
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "onItemClick: You Clicked on a device.");
String deviceName = mBTDevices.get(i).getName();
String deviceAddress = mBTDevices.get(i).getAddress();
Log.d(TAG, "onItemClick: deviceName = " + deviceName);
Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);
//create the bond.
//NOTE: Requires API 17+? I think this is JellyBean
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){
Log.d(TAG, "Trying to pair with " + deviceName);
mBTDevices.get(i).createBond();
}
}
}
XML code primo_fragment:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent">
<Button
android:text="ON/OFF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnONOFF"
android:layout_alignParentEnd="true" />
<Button
android:text="Enable Discoverable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnDiscoverable_on_off"
android:onClick="btnEnableDisable_Discoverable"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnFindUnpairedDevices"
android:text="Discover"
android:onClick="btnDiscover" />
<ListView
android:layout_width="wrap_content"
android:layout_height="150dp"
android:id="#+id/lvNewDevices"
android:layout_marginTop="62dp"
android:layout_alignParentStart="true" />
</RelativeLayout>
device_adapter_view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvDeviceName"
android:textSize="15sp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvDeviceAddress"
android:textSize="15sp"/>
</LinearLayout>
What is wrong with these two button ? I can't find the problem
Please follow this structure to use xml onClick attribute for Fragment. Hope your problem will be resolved.
first activity:
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private Button bt1;
private Button bt2;
private EditText ed1;
private EditText ed2;
private TextView tv3;
static ArrayList<String> s = new ArrayList<>();
static ArrayList<Integer> i = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt1 = (Button)findViewById(R.id.button);
ed1 = (EditText) findViewById(R.id.editText);
ed2 = (EditText)findViewById(R.id.editText2);
bt2 = (Button)findViewById(R.id.button2);
tv3 = (TextView)findViewById(R.id.textView3);
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
s.add(ed1.getText().toString());
i.add(Integer.parseInt(ed2.getText().toString()));
}
});
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
Intent intent = new Intent(MainActivity.this, second.class);
intent.putExtra("key", s);
startActivity(intent);
}
catch(Exception e) {
tv3.setText(e.getMessage());
}
}
});
}
}
Second activity:
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.widget.TextView;
import java.util.ArrayList;
public class second extends AppCompatActivity {
private TextView tv1;
private TextView tv2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
tv1 = (TextView)findViewById(R.id.textView);
tv2 = (TextView)findViewById(R.id.textView2);
ArrayList<String> s = (ArrayList<String>)getIntent().getSerializableExtra("key");
for(int j=0;j<=s.size();j++) {
tv1.setText(s.get(j));
}
}
}
I don't understand the problem in this code. when I click on bt2 to pass the ArrayList from on activity to another then the app just shutdown. I am not able to understand the problem in this code.
Please help me,
I have also updated the manifest.xml for second class.
Are you sure
i.add(Integer.parseInt(ed2.getText().toString()));
in the onClick() call doesnt throw an Exception?
Use a try-catch block around your code in Listener.onClick().
Btw., you can easily use Lambda Exrpessions for ActionListeners.
https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
Please use following construct:-
While Sending:
intent.putStringArrayListExtra("key", s)
While Receiving:
ArrayList<String> s = getIntent().getStringArrayListExtra("key");
Replace your for loop with below, use j< s.size and not j<=s.size
for(int j=0;j<s.size();j++)
{
tv1.setText(s.get(j));
}
You can do like this :
Bundle info= new Bundle();
ArrayList<Product> mas = new ArrayList<Product>();
info.putSerializable("product", mas);
intent.putExtras(info);
And get the values with this:
ArrayList<Product> prod = getIntent().getSerializableExtra(key);
Product class like a serializable object
private class Product implements Serializable {
}
Here it is just how you can pass arraylist between activities.Hope you wil get an idea to solve your issues.
intent.putExtra("key", s);-- this is wrong, you are sending a string but not your arrayList
Try sending with-- intent.putStringArrayListExtra("key", s);
and receiving -- ArrayList<String> stringArray = getIntent().getStringArrayListExtra("key");
hope this will solve your problem...
In your second activity onCreate, add the following code:
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
// Add view
// Must add check extras if null.
Bundle extras = getIntent().getExtras();
ArrayList<String> s = extras.getStringArrayListExtra("key");
// do something
}
In your first activity, send intent with:
Intent intent = new Intent(MainActivity.this, second.class);
intent.putStringArrayListExtra("key", s);
startActivity(intent);
I've tried an sample app with your code. Hope this will help you.
Kindly check my codes.
First Activity
package com.arindam.testapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
public class FirstActivity extends AppCompatActivity {
Button bt1;
EditText ed1;
EditText ed2;
TextView tv3;
ArrayList<String> s = new ArrayList<>();
ArrayList<String> i = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
bt1 = (Button)findViewById(R.id.button);
ed1 = (EditText) findViewById(R.id.editText);
ed2 = (EditText)findViewById(R.id.editText2);
tv3 = (TextView)findViewById(R.id.textView);
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
s.add(ed1.getText().toString());
i.add(ed2.getText().toString());
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("key", s);
intent.putExtra("value", i);
startActivity(intent);
}
catch(Exception e)
{
tv3.setText(e.getMessage());
}
}
});
}
}
First Activity Layout
<?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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#679667"
android:orientation="vertical"
tools:context="com.arindam.testapp.FirstActivity">
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" />
</LinearLayout>
Second Activity
package com.arindam.testapp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import java.util.ArrayList;
public class SecondActivity extends AppCompatActivity {
private TextView tv1;
private TextView tv2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
tv1 = (TextView)findViewById(R.id.textView);
tv2 = (TextView)findViewById(R.id.textView2);
ArrayList<String> s = getIntent().getStringArrayListExtra("key");
for(int j=0;j<s.size();j++)
{
tv1.setText(s.get(j));
}
ArrayList<String> i = getIntent().getStringArrayListExtra("value");
for(int k=0;k<i.size();k++)
{
tv2.setText(i.get(k));
}
}
}
Second Activity Layout
<?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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:background="#229597"
android:orientation="vertical"
tools:context="com.arindam.testapp.SecondActivity">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"/>
</LinearLayout>
If you want to work with key value pairs, go for hashMap.
I want to make a ListView that gets its elements(strings) from user input. I have a button that directs the user to another activity and while in it, the user enters a name and presses another button to come back to the original activity. The same button gets and adds a string to the ArrayAdapter that the ListView uses and displays it as an element in the ListView. It doesn't seem to work and I know it's a stupid mistake, but I'm fresh to android development and this in particular I haven't done before.
Here's all the code:
the MainActivity
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> simpleArray =new ArrayList<String>();
ListAdapter simpleAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
simpleArray);
ListView lv = (ListView) findViewById(R.id.lv);
lv.setAdapter(simpleAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void enterActivity(View view) {
Intent toEnterSecond = new Intent(this, SecondActivity.class);
startActivity(toEnterSecond);
}
}
The second acitivity
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import java.util.ArrayList;
public class SecondActivity extends Activity{
private EditText projectName;
ArrayList simpleArray;
ArrayAdapter simpleAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
projectName = (EditText) findViewById(R.id.eTxt);
}
public void getBack(View view) {
String projectCalling = String.valueOf(projectName.getText());
simpleArray.add(projectCalling);
simpleAdapter.notifyDataSetChanged();
Intent comeBack = new Intent(this, MainActivity.class);
startActivity(comeBack);
}
}
And the layouts
<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"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="80dp"
android:id="#+id/simpleButton"
android:text="click me plox"
android:onClick="enterActivity"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/simpleButton"
android:id="#+id/lv">
</ListView>
</RelativeLayout>
//
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="20dp"
android:text="Enter the name of your project:"
android:id="#+id/txt"/>
<EditText
android:layout_width="200dp"
android:layout_height="40dp"
android:layout_below="#+id/txt"
android:id="#+id/eTxt"/>
<Button
android:layout_width="100dp"
android:layout_height="60dp"
android:layout_below="#+id/eTxt"
android:text="click"
android:onClick="getBack"/>
</RelativeLayout>
Explanation:
You can start SecondActivity with startActivityForResult() instead of startActivity as answered here and in onResultActivity method you can call simpleAdapter.notifyDataSetChanged();. Don't call simpleAdapter.notifyDataSetChanged(); in SecondActivity.
To learn how to use startActivityForResult check this.
Also use finish() instead of
Intent comeBack = new Intent(this, MainActivity.class);
startActivity(comeBack);
in SecondActivity to go back to MainActivity.
Solution:
Change MainActivity enterActivity method to this:
...
public void enterActivity(View view) {
Intent toEnterSecond = new Intent(this, SecondActivity.class);
startActivityForResult(toEnterSecond,1);
}
Add this to end of SecondActivity getBack method:
MainActivity.simpleArray.add(projectCalling);
Intent returnIntent = new Intent();
setResult(RESULT_OK,returnIntent);
finish();
Finally add this new method to MainActivity:
protected void onActivityResult(int requestCode, int resultCode, Intent data{
if (requestCode == 1) {
if(resultCode == RESULT_OK){
((ArrayAdapter) simpleAdapter).notifyDataSetChanged();
}
}
}
To be able to access simpleAdapter, you need to define it outside of onCreate:
public class MainActivity extends ActionBarActivity {
private ListAdapter simpleAdapter;
public static ArrayList<String> simpleArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
simpleArray =new ArrayList<String>();
simpleAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
simpleArray);
...
}
I am working on a bluetooth application but my application crash .Here is my MainActivity.java
package com.race_gurram.bluetoothadapter;
import java.util.ArrayList;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button on, off, get, bring;
private BluetoothAdapter BA;
private Set<BluetoothDevice> pairedDevices;
private ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
on = (Button) findViewById(R.id.on);
off = (Button) findViewById(R.id.off);
get = (Button) findViewById(R.id.get);
bring = (Button) findViewById(R.id.list);
lv = (ListView) findViewById(R.id.listView1);
BA = BluetoothAdapter.getDefaultAdapter();
}
public void on(View view)
{
if(!BA.isEnabled())
{
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn,0);
Toast.makeText(getApplicationContext(), "Turned On", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "Already on", Toast.LENGTH_SHORT).show();
}
}
public void list(View view)
{
pairedDevices = BA.getBondedDevices();
ArrayList list = new ArrayList();
for(BluetoothDevice bt : pairedDevices)
list.add(BA.getName());
Toast.makeText(getApplicationContext(), "Searching for devices", Toast.LENGTH_SHORT).show();
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,list);
lv.setAdapter(adapter);
}
public void get()
{
Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(getVisible,0);
}
public void off()
{
BA.disable();
Toast.makeText(getApplicationContext(), "Turned off", Toast.LENGTH_SHORT).show();
}
#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;
}
}
and this is my activity.xml file
<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:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/on"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="on"
android:text="#string/on" />
<Button
android:id="#+id/get"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="get"
android:text="#string/get" />
<Button
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="list"
android:text="#string/bring" />
<Button
android:id="#+id/off"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="off"
android:text="#string/off" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible" >
</ListView>
</LinearLayout>
</ScrollView>
</RelativeLayout>
Whenever I onclick on a button the application crashes... Please help me out with this .. thank in advance.
On get and off method, there should be a View parameter, right?
public void get(View v) {
Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(getVisible,0);
} public void off(View v) {
BA.disable();
Toast.makeText(getApplicationContext(), "Turned off", Toast.LENGTH_SHORT).show(); }
Perhaps it is when you click the list button. Assuming that the phone has 0 bonded devices,
paired.getBondedDevices() will probably return null and the program crashes due to a NullPointerException.
pairedDevices = BA.getBondedDevices();
ArrayList list = new ArrayList();
if(pairedDevices != null) {
for(BluetoothDevice bt : pairedDevices)
list.add(BA.getName());
}