I am trying to build an Android app that scans for local Miracast connections and connects to them to mirror the screen automatically. I also want the ability to save connections that the user has already connected to before and give them nicknames so the user can recognize them easier. I don't have hardly any experience with Android development, but I have years of experience with Java and other languages.
Right now, the problem I have is my ListView returns a null pointer exception when I try to set the Adapter in the OnCreate method of my MainActivity.
MainActivity.java
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collection;
import android.app.Fragment;
import android.app.Presentation;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.hardware.display.DisplayManager;
import android.media.MediaRouter;
import android.net.NetworkInfo;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pGroup;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.ChannelListener;
import android.net.wifi.p2p.WifiP2pManager.GroupInfoListener;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements OnSharedPreferenceChangeListener{
public static final String TAG = "MainActivity";
private MediaRouter mMediaRouter;
private WifiP2pManager wifimngr;
protected Channel channel;
private boolean paused = false;
private boolean connected = false;
private boolean scanning = false;
protected boolean isWifiEnabled;
protected boolean onCharge;
protected boolean onAlways;
protected MyBroadcastReceiver receiver;
protected ArrayList<WifiP2pDevice> connectionList;
protected int listsize;
private DisplayManager mDisplayManager;
protected ConnectionAdapter adapter;
protected ArrayList<WifiP2pDevice> devices;
private final IntentFilter intentFilter = new IntentFilter();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectionList = new ArrayList<WifiP2pDevice>();
adapter = new ConnectionAdapter(this, devices);
ListView listview = (ListView) findViewById(R.id.list);
listview.setAdapter(adapter);
//Connection newCon = new Connection("My address", "My nickname", false);
//adapter.add(newCon);
//newCon = new Connection("My address2", "My nickname2", true);
//adapter.add(newCon);
// Indicates a change in the Wi-Fi P2P status.
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
// Indicates a change in the list of available peers.
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
// Indicates the state of Wi-Fi P2P connectivity has changed.
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
// Indicates this device's details have changed.
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
mDisplayManager = (DisplayManager)this.getSystemService(Context.DISPLAY_SERVICE);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
wifimngr = (WifiP2pManager)getSystemService(Context.WIFI_P2P_SERVICE);
channel = wifimngr.initialize(this, getMainLooper(), new ChannelListener() {
public void onChannelDisconnected() {
channel = null;
}
});
}
PeerListListener myPeerListListener =
new PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
// Out with the old, in with the new.
devices.clear();
devices.addAll(peerList.getDeviceList());
// If an AdapterView is backed by this data, notify it
// of the change. For instance, if you have a ListView of available
// peers, trigger an update.
//((ConnectionAdapter) getListAdapter()).notifyDataSetChanged();
if (devices.size() == 0) {
Log.d("TAG", "No devices found");
return;
}
}
};
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
openSettings();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
public void updateStatus(String input)
{
TextView edit = (TextView) findViewById(R.id.statusText);
edit.setText(input);
}
//What happens when the pause button is clicked
public void pauseConnections(View view)
{
if(!paused)
{
updateStatus("Streaming");
mMediaRouter = (MediaRouter) this.getSystemService(Context.MEDIA_ROUTER_SERVICE);
MediaRouter.RouteInfo route = mMediaRouter.getSelectedRoute(mMediaRouter.ROUTE_TYPE_LIVE_VIDEO);
if (route != null) {
Display presentationDisplay = route.getPresentationDisplay();
if (presentationDisplay != null) {
Presentation presentation = new Presentation(this, presentationDisplay, 0);
presentation.show();
}
}
ProgressBar pg = (ProgressBar) findViewById(R.id.progressBar1);
pg.setVisibility(View.VISIBLE);
Button edit = (Button) findViewById(R.id.pauseButton);
edit.setText("Pause");
edit = (Button) findViewById(R.id.scanbutton);
edit.setEnabled(false);
}else
{
updateStatus("Paused");
MediaRouter.RouteInfo route = mMediaRouter.getSelectedRoute(mMediaRouter.ROUTE_TYPE_LIVE_VIDEO);
if (route != null) {
Display presentationDisplay = route.getPresentationDisplay();
if (presentationDisplay != null) {
Presentation presentation = new Presentation(this, presentationDisplay, 0);
presentation.show();
}
}
ProgressBar pg = (ProgressBar) findViewById(R.id.progressBar1);
pg.setVisibility(View.INVISIBLE);
Button edit = (Button) findViewById(R.id.pauseButton);
edit.setText("Stream");
edit = (Button) findViewById(R.id.scanbutton);
edit.setEnabled(true);
}
paused=!paused;
}
//What happens when the scan button is clicked
public void scanConnections(View view)
{
if(!scanning)
{
updateStatus("Scanning...");
ProgressBar pg = (ProgressBar) findViewById(R.id.progressBar1);
pg.setVisibility(View.VISIBLE);
wifimngr.setMiracastMode(1);
wifimngr.discoverPeers(channel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
}
#Override
public void onFailure(int reason) {
if(reason == 1)
{
updateStatus("Failed to get devices. Device not supported");
}else if(reason == 2)
{
updateStatus("Failed to get devices. Busy");
}else
{
updateStatus("Failed to get devices. Error");
}
ProgressBar pg = (ProgressBar) findViewById(R.id.progressBar1);
pg.setVisibility(View.INVISIBLE);
Button edit = (Button) findViewById(R.id.scanbutton);
edit.setText("Scan");
edit = (Button) findViewById(R.id.pauseButton);
edit.setEnabled(true);
scanning=!scanning;
}
});
Button edit = (Button) findViewById(R.id.scanbutton);
edit.setText("Stop");
edit = (Button) findViewById(R.id.pauseButton);
edit.setEnabled(false);
}else
{
ProgressBar pg = (ProgressBar) findViewById(R.id.progressBar1);
pg.setVisibility(View.INVISIBLE);
wifimngr.removeGroup(channel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
}
#Override
public void onFailure(int reason) {
if(reason == 1)
{
updateStatus("Failed to disconnect. Device not supported");
}else if(reason == 2)
{
updateStatus("Failed to disconnect. Busy");
}else
{
updateStatus("Failed to disconnect. Error");
}
ProgressBar pg = (ProgressBar) findViewById(R.id.progressBar1);
pg.setVisibility(View.INVISIBLE);
}
});
updateStatus("Waiting");
Button edit = (Button) findViewById(R.id.scanbutton);
edit.setText("Scan");
edit = (Button) findViewById(R.id.pauseButton);
edit.setEnabled(true);
}
scanning=!scanning;
}
public void openSettings()
{
Intent intent = new Intent(this, SettingsActivity.class);
intent.putExtra("onCharge", onCharge);
intent.putExtra("onAlways", onAlways);
startActivity(intent);
}
public void onCheckboxClicked(View view)
{
boolean checked = ((CheckBox) view).isChecked();
}
public void onConnectionClick(View view)
{
DialogFragment dialog = new ConnDialogFragment();
dialog.show(getSupportFragmentManager(), "NoticeDialogFragment");
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals("pref_onCharge")) {
// Set summary to be the user-description for the selected value
onCharge = sharedPreferences.getBoolean(key, true);
}else if (key.equals("pref_onAlways")) {
// Set summary to be the user-description for the selected value
onAlways = sharedPreferences.getBoolean(key, false);
}else if(key.equals("pref_listsize"))
{
listsize = sharedPreferences.getInt(key, 0);
}
}
private void onPeersChanged(Intent intent)
{
wifimngr.requestPeers(channel, myPeerListListener);
}
private void onConnectionChanged(Intent intent) {
WifiP2pInfo p2pInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_INFO);
NetworkInfo netInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if (netInfo.isConnected())
{
updateInfos();
useNetwork(p2pInfo);
} else
{
//resetInfos();
}
}
public void connect() {
// Picking the first device found on the network.
WifiP2pDevice device = devices.get(0);
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
config.wps.setup = WpsInfo.PBC;
wifimngr.connect(channel, config, new ActionListener() {
#Override
public void onSuccess() {
// WiFiDirectBroadcastReceiver will notify us. Ignore for now.
}
#Override
public void onFailure(int reason) {
Toast.makeText(MainActivity.this, "Connect failed. Retry.",
Toast.LENGTH_SHORT).show();
}
});
}
public void onConnectionInfoAvailable(final WifiP2pInfo info) {
// InetAddress from WifiP2pInfo struct.
InetAddress groupOwnerAddress = info.groupOwnerAddress;
// After the group negotiation, we can determine the group owner.
if (info.groupFormed && info.isGroupOwner) {
// Do whatever tasks are specific to the group owner.
// One common case is creating a server thread and accepting
// incoming connections.
} else if (info.groupFormed) {
// The other device acts as the client. In this case,
// you'll want to create a client thread that connects to the group
// owner.
}
}
private void updateInfos() {
wifimngr.requestGroupInfo(channel,
new GroupInfoListener() {
#Override
public void onGroupInfoAvailable(WifiP2pGroup group)
{
String name = group.getNetworkName();
String passphrase = group.getPassphrase();
Collection<WifiP2pDevice> devices = group.getClientList();
// do stuff with devices
// but ... No way to get their IP addresses :(
}
});
}
private void useNetwork(WifiP2pInfo p2pInfo) {
if (!p2pInfo.isGroupOwner) {
InetAddress addr = p2pInfo.groupOwnerAddress;
try
{
Socket s = new Socket(addr, 1234);
}catch(IOException e)
{
e.printStackTrace();
}
//use the socket
} else {
try{
//groupOwnerAddress is our local address
ServerSocket serverSocket = new ServerSocket(1234);
Socket s = serverSocket.accept();
}catch(IOException e)
{
e.printStackTrace();
}
//use the socket
}
}
private void connect(WifiP2pDevice device) {
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
config.wps.setup = WpsInfo.PBC; // choose between what is available on the device.
wifimngr.connect(channel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
}
#Override
public void onFailure(int reason) {
}
});
}
protected void setIsWifiP2pEnabled(boolean isEnabled)
{
isWifiEnabled = isEnabled;
}
/** register the BroadcastReceiver with the intent values to be matched */
#Override
public void onResume() {
super.onResume();
receiver = new MyBroadcastReceiver(wifimngr, channel, this);
registerReceiver(receiver, intentFilter);
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
}
ConnectionAdapter.java
import java.util.ArrayList;
import android.content.Context;
import android.net.wifi.p2p.WifiP2pDevice;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class ConnectionAdapter extends ArrayAdapter<WifiP2pDevice> {
public ConnectionAdapter(Context context, ArrayList<WifiP2pDevice> connections)
{
super(context, R.layout.connection, connections);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
WifiP2pDevice con = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.connection, parent, false);
viewHolder.name = (TextView) convertView.findViewById(R.id.conName);
viewHolder.nickname = (TextView) convertView.findViewById(R.id.conNickname);
convertView.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data into the template view using the data object
viewHolder.name.setText(con.deviceName);
viewHolder.nickname.setText(con.primaryDeviceType);
// Return the completed view to render on screen
return convertView;
}
private static class ViewHolder {
TextView name;
TextView nickname;
}
}
**BroadcastReceiver.java**
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.util.Log;
public class MyBroadcastReceiver extends BroadcastReceiver{
protected WifiP2pManager wifimngr;
protected Channel channel;
protected MainActivity activity;
public MyBroadcastReceiver(WifiP2pManager iwifimngr, Channel ichannel, MainActivity iactivity)
{
super();
wifimngr=iwifimngr;
channel=ichannel;
activity=iactivity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
// Determine if Wifi P2P mode is enabled or not, alert
// the Activity.
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
activity.setIsWifiP2pEnabled(true);
} else {
activity.setIsWifiP2pEnabled(false);
}
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// Request available peers from the wifi p2p manager. This is an
// asynchronous call and the calling activity is notified with a
// callback on PeerListListener.onPeersAvailable()
if (wifimngr != null) {
wifimngr.requestPeers(channel, (PeerListListener) activity.getFragmentManager()
.findFragmentById(R.id.list));
}
Log.d(MainActivity.TAG, "P2P peers changed");
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
if (wifimngr == null) {
return;
}
NetworkInfo networkInfo = (NetworkInfo) intent
.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected()) {
// we are connected with the other device, request connection
// info to find group owner IP
//DeviceDetailFragment fragment = (DeviceDetailFragment) activity
// .getFragmentManager().findFragmentById(R.id.frag_detail);
//wifimngr.requestConnectionInfo(channel, fragment);
} else {
// It's a disconnect
//activity.resetData();
}
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
DeviceListFragment fragment = (DeviceListFragment) activity.getFragmentManager()
.findFragmentById(R.id.list);
fragment.updateThisDevice((WifiP2pDevice) intent.getParcelableExtra(
WifiP2pManager.EXTRA_WIFI_P2P_DEVICE));
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.hpconcept.miracastconnector.MainActivity"
tools:ignore="MergeRootFrame" >
<ListView
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="250dp"
android:layout_marginTop="0dp"
android:layout_marginBottom="0dp"
android:paddingTop="0dp"
android:textSize="20sp" >
</ListView>
<View android:id="#+id/strut"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="200dp"
android:layout_below="#android:id/list"
android:layout_centerHorizontal="true"/>
<Button
android:id="#+id/scanbutton"
android:text="#string/scan_string"
android:layout_height="wrap_content"
android:layout_below="#android:id/list"
android:layout_width="0dp"
android:layout_alignParentBottom="true"
android:onClick="scanConnections"
android:layout_alignRight="#id/strut"
android:layout_alignParentLeft="true"
/>
<Button
android:id="#+id/pauseButton"
android:text="#string/stream_string"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:onClick="pauseConnections"
android:layout_gravity="bottom"
android:layout_alignLeft="#id/strut"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"
android:layout_below="#android:id/list"
android:layout_toRightOf="#+id/scanbutton" />
<TextView
android:id="#+id/statusText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/pauseButton"
android:layout_alignLeft="#+id/pauseButton"
android:layout_marginLeft="42dp"
android:gravity="center"
android:text="#string/waiting_string" />
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/statusText"
android:layout_alignLeft="#+id/pauseButton"
android:layout_marginLeft="24dp"
android:visibility="invisible" />
</RelativeLayout>
So this whole project is basically turning into me trying to duct-tape together various pieces of sample code from around the internet. I could really use some help. I'm trying to use Google's Android development pages, but I don't always know where to put their snippets of code. I was trying to make my own Connection class, that would hold the WifiP2pDevice's in an arraylist along with the nicknames and other data, but I couldn't get it to work for some reason. So now my priority is just getting the program to run and find connections. I did finish the GUI to the best of my knowledge. I might need to change it or something though.
This is not all of my code. If I posted it all, this question would be huge. lol If you want to see it all, let me know.
So I found this code for anyone interested and this works perfectly:
try
{
Log.d("DEBUG", "open WiFi display settings in HTC");
startActivity(new Intent("com.htc.wifidisplay.CONFIGURE_MODE_NORMAL"));
} catch (Exception e)
{
try
{
Log.d("DEBUG", "open WiFi display settings in Samsung");
startActivity(new Intent("com.samsung.wfd.LAUNCH_WFD_PICKER_DLG"));
}catch (Exception e2)
{
Log.d("DEBUG", "open WiFi display settings in stock Android");
startActivity(new Intent("android.settings.WIFI_DISPLAY_SETTINGS"));
}
}
I got rid of the listview for now since I don't need to scan for devices with WifiP2p anymore. When this setting opens, it will connect to a nearby display automatically.
The only thing I need is to figure out a way for the settings screen to close after it has connected to a display. I have tried emulating a back button press but it only gets emulated when the user returns to the app himself. Then it backs out of the app.
Related
I am working on this project where I am supposed to utilize Bluetooth beacons to create an indoor map with direction finding(mobile app). This is how the idea is supposed to go: mobile device interacting with BLE devices through BLE scanner, scanner gets the device information (MAC-address, rssi..etc) So far what I've done is I am able to make the scanner work and I have a map with an indoor floor plan layered.
What I am trying to do now is to integrate the BLE scanner with the map such that the scanner works at the backend automatically scanning and connecting to BLE devices, therefore using the information(specifically RSSI values) to work out the distance between the device and beacon. I am totally lost on what and how to do it as it is my first time developing a mobile application.
Here is the image of the map as stated above.
map with floor plan
So far I have only tried to copy the codes of the BLE scanner into the project of the map but I have no clue how to merge the two such that it gives me the above stated outcome
Here are the codes of the BLE scanner:
DeviceScanActivity.java
package com.example.android.bluetoothlegatt;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.ScanResult;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
/**
* Activity for scanning and displaying available Bluetooth LE devices.
*/
public class DeviceScanActivity extends ListActivity {
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 123;
private LeDeviceListAdapter mLeDeviceListAdapter;
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private Handler mHandler;
private static final int REQUEST_ENABLE_BT = 1;
// Stops scanning after 10 seconds.
private static final long SCAN_PERIOD = 10000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setTitle(R.string.title_devices);
mHandler = new Handler();
//need to be able to access location before can scan
//for when build ver sdk 23+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
}
// Use this check to determine whether BLE is supported on the device. Then you can
// selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// Checks if Bluetooth is supported on the device.
if (mBluetoothAdapter == null) {
Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
finish();
return;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
if (!mScanning) {
menu.findItem(R.id.menu_stop).setVisible(false);
menu.findItem(R.id.menu_scan).setVisible(true);
menu.findItem(R.id.menu_refresh).setActionView(null);
} else {
menu.findItem(R.id.menu_stop).setVisible(true);
menu.findItem(R.id.menu_scan).setVisible(false);
menu.findItem(R.id.menu_refresh).setActionView(
R.layout.actionbar_indeterminate_progress);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_scan:
mLeDeviceListAdapter.clear();
scanLeDevice(true);
break;
case R.id.menu_stop:
scanLeDevice(false);
break;
}
return true;
}
#Override
protected void onResume() {
super.onResume();
// Ensures Bluetooth is enabled on the device. If Bluetooth is not currently enabled,
// fire an intent to display a dialog asking the user to grant permission to enable it.
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
// Initializes list view adapter.
mLeDeviceListAdapter = new LeDeviceListAdapter();
setListAdapter(mLeDeviceListAdapter);
scanLeDevice(true);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// User chose not to enable Bluetooth.
if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
finish();
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onPause() {
super.onPause();
scanLeDevice(false);
mLeDeviceListAdapter.clear();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
if (device == null) return;
final Intent intent = new Intent(this, DeviceControlActivity.class);
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName());
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
if (mScanning) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
mScanning = false;
}
startActivity(intent);
}
private void scanLeDevice(final boolean enable) {
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
invalidateOptionsMenu();
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
invalidateOptionsMenu();
}
// Adapter for holding devices found through scanning.
private class LeDeviceListAdapter extends BaseAdapter {
private ArrayList<BluetoothDevice> mLeDevices;
private LayoutInflater mInflator;
public LeDeviceListAdapter() {
super();
mLeDevices = new ArrayList<BluetoothDevice>();
mInflator = DeviceScanActivity.this.getLayoutInflater();
}
public void addDevice(BluetoothDevice device) {
if(!mLeDevices.contains(device)) {
mLeDevices.add(device);
}
}
public BluetoothDevice getDevice(int position) {
return mLeDevices.get(position);
}
public void clear() {
mLeDevices.clear();
}
#Override
public int getCount() {
return mLeDevices.size();
}
#Override
public Object getItem(int i) {
return mLeDevices.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
// General ListView optimization code.
if (view == null) {
view = mInflator.inflate(R.layout.listitem_device, null);
viewHolder = new ViewHolder();
viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
BluetoothDevice device = mLeDevices.get(i);
final String deviceName = device.getName();
final String deviceAddress = device.getAddress();
if (deviceName != null && deviceName.length() > 0 && deviceAddress.contains("00:15:88:07"))
viewHolder.deviceName.setText(device.getName());
else
viewHolder.deviceName.setText(R.string.unknown_device);
// viewHolder.deviceAddress.setText(R.string.invalid_address);
viewHolder.deviceAddress.setText(device.getAddress());
return view;
}
}
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mLeDeviceListAdapter.addDevice(device);
mLeDeviceListAdapter.notifyDataSetChanged();
}
});
}
};
static class ViewHolder {
TextView deviceName;
TextView deviceAddress;
}
}
I would appreciate if anyone could help me with this problem I have been trying to solve for the past few days. Thank you very much!
Alright so currently my app turns on bluetooth on my device and then lists all paired devices in a List View. I am trying to make it so when the item in the list view is clicked it will connect to the device (primarily for bluetooth speakers). Below i have listed my main java file with all the code that runs my app. If anyone could get me going in the right direction id appreciate it. Also this is my first project working with bluetooth.
package com.applie.itchaboynathan.appv2;
import android.support.v7.app.AppCompatActivity;
import java.io.IOException;
import java.net.Socket;
import java.util.UUID;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.view.MenuItem;
import android.widget.Toast;
import android.bluetooth.BluetoothAdapter;
import android.widget.SeekBar;
import android.widget.TextView;
import android.content.Intent;
import android.widget.ListView;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothProfile;
import java.util.ArrayList;
import android.widget.ArrayAdapter;
import java.util.Set;
import android.os.Handler;
public class MainActivity extends AppCompatActivity {
private static SeekBar seek_bar;
private static TextView text_view;
private BluetoothAdapter BA;
private Set<BluetoothDevice>pairedDevices;
Handler handler = new Handler();
ListView lv;
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
volumeBar();
BA = BluetoothAdapter.getDefaultAdapter();
lv = (ListView)findViewById(R.id.deviceList);
iv = (ImageView)findViewById(R.id.imgConnection);
//define menu button
ImageButton menubutton = (ImageButton)findViewById(R.id.ibtnMenu);
//enables the button to show a menu
menubutton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v){
final PopupMenu popupMenu = new PopupMenu(getApplicationContext(),v);
popupMenu.inflate(R.menu.main_menu);
popupMenu.show();
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item){
switch (item.getItemId()) {
case R.id.connect:
//code for connect item
//Delay so the list creates
handler.postDelayed(new Runnable() {
#Override
public void run(){
list();
visible();
iv.setImageResource(R.mipmap.ic_checked);
}
}, 4200);
turnOn();
return true;
case R.id.disconnect:
//code for music item
turnOff();
iv.setImageResource(R.mipmap.ic_disconnected);
listClear();
return true;
case R.id.music:
//code for music item
return true;
case R.id.play:
//code for play item
return true;
case R.id.pause:
//code for pause item
return true;
}
return false;
}
});
}
});//end of button
}
//bluettoth enabler
public void turnOn(){
if (!BA.isEnabled()) {
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
Toast.makeText(getApplicationContext(), "Turned on",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Already on", Toast.LENGTH_LONG).show();
}
}
//bluetooth disable
public void turnOff(){
BA.disable();
Toast.makeText(getApplicationContext(), "Turned off" ,Toast.LENGTH_LONG).show();
}
public void visible(){
Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(getVisible, 0);
}
public void listClear(){
lv.setAdapter(null);
}
public void list(){
pairedDevices = BA.getBondedDevices();
ArrayList list = new ArrayList();
for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());
Toast.makeText(getApplicationContext(), "Showing Paired Devices",Toast.LENGTH_SHORT).show();
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
//volume bar code
public void volumeBar(){
seek_bar = (SeekBar)findViewById(R.id.seekBar);
text_view =(TextView)findViewById(R.id.txtVolumeLvl);
text_view.setText("Volume : " + seek_bar.getProgress() + " % ");
seek_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener(){
int progress_value;
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progress_value = progress;
text_view.setText("Volume : " + progress + " % ");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
text_view.setText("Volume : " + progress_value + " % ");
}
}
);
}
//end volume bar
}
Try this:
ArrayList list = new ArrayList();
public void list(){
pairedDevices = BA.getBondedDevices();
for(BluetoothDevice bt : pairedDevices) list.add(bt.getName());
Toast.makeText(getApplicationContext(), "Showing Paired Devices",Toast.LENGTH_SHORT).show();
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener () {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
String selected = list.get(position);
for (Iterator<BluetoothDevice> it = pairedDevices.iterator(); it.hasNext(); ) {
BluetoothDevice bt = it.next();
if (bt.getName().equals(selected){
//connect to device
}
}
});
}
You have use BluetoothSocketfor connecting bluetooth.
use the below code to connect.
private BluetoothAdapter mBluetoothAdarpter;
private BluetoothSocket mBtSocket;
private BluetoothDevice mBTDevice;
private static final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
..
..
private boolean connectToDevice(String iAdress) {
try {
if(mBluetoothAdarpter == null) mBluetoothAdarpter = BluetoothAdapter.getDefaultAdapter();
mBTDevice = mBluetoothAdarpter.getRemoteDevice(iAdress);
mBtSocket = mBTDevice.createRfcommSocketToServiceRecord(SPP_UUID);
mBtSocket.connect();
return true;
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
I am getting a NullPointerException at line 67 while trying to set a listView with a chat adapter. Here is the class:
I have placed ** around the line I am getting the NullPointerException on. I'm not really understading why its returning as null when I'm setting messageAdapter to a new object of an inner class called ChatAdapter(this).
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MessageListActivity extends AppCompatActivity {
/**
* Whether or not the activity is in two-pane mode, i.e. running on a tablet
* device.
*/
ListView listView;
Button sendButton;
ArrayList<String> arrayList = new ArrayList<String>();
ChatDatabaseHelper Cdb;
private boolean mTwoPane;
ChatAdapter messageAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message_list);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitle(getTitle());
listView = (ListView)findViewById(R.id.chatListView);
final EditText editText = (EditText)findViewById(R.id.messageText);
sendButton = (Button)findViewById(R.id.sendButton);
messageAdapter = new ChatAdapter(this); // chatAdapter is a built in adapater
**listView.setAdapter(messageAdapter);**
Cdb = new ChatDatabaseHelper(this);
Cursor cursor = Cdb.getMessages(); // get messages method is of type Cursor from database helper class
// cursor will move through the database to find the next text if there is any.
while (cursor.moveToNext()) { arrayList.add(cursor.getString(cursor.getColumnIndex(Cdb.KEY_MESSAGE))); }
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) { // on click listener for the send button
String chatText = editText.getText().toString(); // changing editText to String
arrayList.add(chatText); // adding the string from EditTest to arrayList
boolean isInserted = Cdb.insertData(chatText); // inserting the message text into the database
if(isInserted = true)
{ Toast.makeText(MessageListActivity.this,"Message Sent",Toast.LENGTH_SHORT).show(); } // if the message inserts into the database this toast will show
else {
Toast.makeText(MessageListActivity.this,"Message not Sent",Toast.LENGTH_SHORT).show(); } // if message does not nter the database this toast will show
messageAdapter.notifyDataSetChanged(); // notifying the adapter that a message has been sent, changing from incoming to outgoing
editText.setText(" "); // set the text on the send button to blank.
} // end of onClick view
}); // end of onClickListener
if (findViewById(R.id.message_detail_container) != null) {
// The detail container view will be present only in the
// large-screen layouts (res/values-w900dp).
// If this view is present, then the
// activity should be in two-pane mode.
mTwoPane = true;
}
}
class ChatAdapter extends ArrayAdapter<String> { // custom adapter class // when youc all the adapter it forms the for loop for you.
public ChatAdapter(MessageListActivity ctx) {
super(ctx, 0);
} // default constructor
// method to return the number of rows that will be in your array
// will tell how many times to run a for loop
public int getCount(){ return arrayList.size(); } // will return the size of the array
public String getItem(int position){ return arrayList.get(position); } // will return the item at position
// getview method
#Override
public View getView(int position, final View convertView, ViewGroup parent) {// inner class
LayoutInflater Inflater = MessageListActivity.this.getLayoutInflater(); // an inflater inflates the xml layout into a view.
View result = null;
if(position%2 == 0){ // if position number in the array is odd do this, if number is even, do this.
result = Inflater.inflate(R.layout.chat_row_incoming, null); // depending on the position, show layout incoming
} else {
result = Inflater.inflate(R.layout.chat_row_outgoing,null); // depending on the position, show layout outgoing
}
TextView message = (TextView)result.findViewById(R.id.messageText); // creating a message of type TextView connected to messageText
final String messageText = getItem(position) ;
message.setText(messageText);
result.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(MessageDetailFragment.ARG_ITEM_ID,messageText );
MessageDetailFragment fragment = new MessageDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.message_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, MessageDetailActivity.class);
intent.putExtra(MessageDetailFragment.ARG_ITEM_ID,messageText );
context.startActivity(intent);
}
}
});
return result; // return the view which is the Inflater.
}
} // end of chat adapter class
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
recyclerView.setAdapter(new SimpleItemRecyclerViewAdapter(DummyContent.ITEMS));
}
public class SimpleItemRecyclerViewAdapter
extends RecyclerView.Adapter<SimpleItemRecyclerViewAdapter.ViewHolder> {
private final List<DummyContent.DummyItem> mValues;
public SimpleItemRecyclerViewAdapter(List<DummyContent.DummyItem> items) {
mValues = items;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.message_list_content, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mValues.get(position);
holder.mIdView.setText(mValues.get(position).id);
holder.mContentView.setText(mValues.get(position).content);
holder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mTwoPane) {
Bundle arguments = new Bundle();
arguments.putString(MessageDetailFragment.ARG_ITEM_ID, holder.mItem.id);
MessageDetailFragment fragment = new MessageDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.replace(R.id.message_detail_container, fragment)
.commit();
} else {
Context context = v.getContext();
Intent intent = new Intent(context, MessageDetailActivity.class);
intent.putExtra(MessageDetailFragment.ARG_ITEM_ID, holder.mItem.id);
context.startActivity(intent);
}
}
});
}
#Override
public int getItemCount() {
return mValues.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView mIdView;
public final TextView mContentView;
public DummyContent.DummyItem mItem;
public ViewHolder(View view) {
super(view);
mView = view;
mIdView = (TextView) view.findViewById(R.id.id);
mContentView = (TextView) view.findViewById(R.id.content);
}
#Override
public String toString() {
return super.toString() + " '" + mContentView.getText() + "'";
}
}
}
xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.ChatWindow">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/chatListView"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="false"
android:layout_alignWithParentIfMissing="false"
android:layout_above="#+id/sendButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/sendButton"
android:id="#+id/sendButton"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:singleLine="true" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/messageText"
android:layout_toStartOf="#id/sendButton"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:enabled="true"
/>
</RelativeLayout>
just try
messageAdapter = new ChatAdapter(MessageListActivity .this);
I'm trying to create the favorites list from Json Objects which I received by URL.
When I got Json array, I defined methods OnItemLongClickListener and OnItemClickListener that get different things:
The OnItemClickListener method has to open another activity with description of product
The OnItemLongClickListener method has to add product to favorite list
The Problem that method OnItemClickListener which I defined in MainActivity is override method OnItemLongClickListener which I defined in FragmentActivty and the method OnItemLongClickListener doesn't work at all then I tried to define both methods in FragmentActivity but after that both methods don't work at all.
Is there any way to determine this problem?
Main Activity:
package com.boom.kayakapp.activities;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.boom.kayakapp.R;
import com.boom.kayakapp.adapters.AirlinesAdapter;
import com.boom.kayakapp.controllers.AppController;
import com.boom.kayakapp.fragment.AirlinesFragment;
import com.boom.kayakapp.fragment.FavoriteFragment;
import com.boom.kayakapp.model.Airlines;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity {
private Fragment contentFragment;
AirlinesFragment airlinesFragment;
FavoriteFragment favoriteFragment;
// JSON Node names
public static final String TAG_NAME = "name";
public static final String TAG_PHONE = "phone";
public static final String TAG_SITE = "site";
public static final String TAG_LOGO = "logoURL";
public static final String TAG_CODE = "code";
// Log tag
private static final String TAG = MainActivity.class.getSimpleName();
// Airlines json url
private static final String url = "https://www.kayak.com/h/mobileapis/directory/airlines";
public ProgressDialog pDialog;
public List<Airlines> airlinesList = new ArrayList<Airlines>();
public ListView listView;
public AirlinesAdapter adapter;
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
listView = (ListView) findViewById(R.id.list);
adapter = new AirlinesAdapter(this, airlinesList);
listView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Listview on item click listener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String phone = ((TextView) view.findViewById(R.id.phone))
.getText().toString();
String site = ((TextView) view.findViewById(R.id.site))
.getText().toString();
String logoURL = String.valueOf(((ImageView) view.findViewById(R.id.logoURL)));
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_PHONE, phone);
in.putExtra(TAG_SITE, site);
in.putExtra(TAG_LOGO, logoURL);
startActivity(in);
}
});
// changing action bar color
getSupportActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#1b1b1b")));
// Creating volley request obj
JsonArrayRequest airlinesReq = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
Airlines airlines = new Airlines();
airlines.setName(obj.getString("name"));
airlines.setLogoURL(obj.getString("logoURL"));
airlines.setPhone(obj.getString("phone"));
airlines.setCode(obj.getInt("code"));
airlines.setSite(obj.getString("site"));
// adding airlines to movies array
airlinesList.add(airlines);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(airlinesReq);
FragmentManager fragmentManager = getSupportFragmentManager();
/*
* This is called when orientation is changed.
*/
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("content")) {
String content = savedInstanceState.getString("content");
if (content.equals(FavoriteFragment.ARG_ITEM_ID)) {
if (fragmentManager.findFragmentByTag(FavoriteFragment.ARG_ITEM_ID) != null) {
setFragmentTitle(R.string.favorites);
contentFragment = fragmentManager
.findFragmentByTag(FavoriteFragment.ARG_ITEM_ID);
}
}
}
if (fragmentManager.findFragmentByTag(AirlinesFragment.ARG_ITEM_ID) != null) {
airlinesFragment = (AirlinesFragment) fragmentManager
.findFragmentByTag(AirlinesFragment.ARG_ITEM_ID);
contentFragment = airlinesFragment;
}
} else {
airlinesFragment = new AirlinesFragment();
// setFragmentTitle(R.string.app_name);
switchContent(airlinesFragment, AirlinesFragment.ARG_ITEM_ID);
}
}
#Override
public void onDestroy () {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#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;
}
#Override
protected void onSaveInstanceState(Bundle outState) {
if (contentFragment instanceof FavoriteFragment) {
outState.putString("content", FavoriteFragment.ARG_ITEM_ID);
} else {
outState.putString("content", AirlinesFragment.ARG_ITEM_ID);
}
super.onSaveInstanceState(outState);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_favorites:
setFragmentTitle(R.string.favorites);
favoriteFragment = new FavoriteFragment();
switchContent(favoriteFragment, FavoriteFragment.ARG_ITEM_ID);
return true;
}
return super.onOptionsItemSelected(item);
}
public void switchContent(Fragment fragment, String tag) {
FragmentManager fragmentManager = getSupportFragmentManager();
while (fragmentManager.popBackStackImmediate()) ;
if (fragment != null) {
FragmentTransaction transaction = fragmentManager
.beginTransaction();
transaction.replace(R.id.content_frame, fragment, tag);
//Only FavoriteFragment is added to the back stack.
if (!(fragment instanceof AirlinesFragment)) {
transaction.addToBackStack(tag);
}
transaction.commit();
contentFragment = fragment;
}
}
protected void setFragmentTitle(int resourseId) {
setTitle(resourseId);
getSupportActionBar().setTitle(resourseId);
}
/*
* We call super.onBackPressed(); when the stack entry count is > 0. if it
* is instanceof ProductListFragment or if the stack entry count is == 0, then
* we finish the activity.
* In other words, from ProductListFragment on back press it quits the app.
*/
#Override
public void onBackPressed() {
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
super.onBackPressed();
} else if (contentFragment instanceof AirlinesFragment
|| fm.getBackStackEntryCount() == 0) {
finish();
}
}
}
FragmentActivity:
package com.boom.kayakapp.fragment;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.boom.kayakapp.R;
import com.boom.kayakapp.adapters.AirlinesAdapter;
import com.boom.kayakapp.model.Airlines;
import com.boom.kayakapp.util.SharedPreference;
import java.util.ArrayList;
import java.util.List;
public class AirlinesFragment extends Fragment implements OnItemClickListener, OnItemLongClickListener{
public static final String ARG_ITEM_ID = "airlines_list";
Activity activity;
ListView airlinesListView;
List<Airlines> airlines;
AirlinesAdapter airlinesAdapter;
public AirlinesFragment() {
airlines = new ArrayList<>();
}
SharedPreference sharedPreference;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
sharedPreference = new SharedPreference();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_list, container,
false);
findViewsById(view);
airlinesAdapter = new AirlinesAdapter(activity, airlines);
airlinesListView.setAdapter(airlinesAdapter);
airlinesListView.setOnItemClickListener(this);
airlinesListView.setOnItemLongClickListener(this);
return view;
}
private void findViewsById(View view) {
airlinesListView = (ListView) view.findViewById(R.id.list);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Airlines airlines = (Airlines) parent.getItemAtPosition(position);
Toast.makeText(activity, airlines.toString(), Toast.LENGTH_LONG).show();
}
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
int position, long arg3) {
ImageView button = (ImageView) view.findViewById(R.id.favorite_button);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(activity, airlines.get(position));
Toast.makeText(activity,
activity.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.heart_red);
} else {
sharedPreference.removeFavorite(activity, airlines.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.heart_grey);
Toast.makeText(activity,
activity.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
#Override
public void onResume() {
getActivity().setTitle(R.string.app_name);
super.onResume();
}
}
In my way I deleted definition both Methods from FavoriteFragment and defined it in MainActivity:
Json Array
listView = (ListView) findViewById(R.id.list);
adapterAirlines = new AirlinesAdapter(this, airlinesList);
listView.setAdapter(adapterAirlines);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// Listview OnItemClickListener
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String phone = ((TextView) view.findViewById(R.id.phone))
.getText().toString();
String site = ((TextView) view.findViewById(R.id.site))
.getText().toString();
String logoURL = String.valueOf(((ImageView) view.findViewById(R.id.logoURL)));
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_PHONE, phone);
in.putExtra(TAG_SITE, site);
in.putExtra(TAG_LOGO, logoURL);
startActivity(in);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
ImageView button = (ImageView) view.findViewById(R.id.favorite_button);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(MainActivity.this, airlinesList.get(position));
Toast.makeText(MainActivity.this,
MainActivity.this.getResources().getString(R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.heart_red);
} else {
sharedPreference.removeFavorite(MainActivity.this, airlinesList.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.heart_grey);
Toast.makeText(MainActivity.this,
MainActivity.this.getResources().getString(R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
return true;
}
});
now it works
I need help with knowing how to get dialogfragment act when entered a value then pressed okay button or cancel button.
Below are classes ActivityA.java, BasicDialogFragment.java, fragment_basic_dialog.xml and activity_a.xml.
That's all the code you need for this question. Thanks in advance.
ActivityA
package internal.android.com.helloworld;
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.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ActivityA extends ActionBarActivity implements BasicDialogFragment.OnNameEnteredListener {
private Button dialogKnapp = null;
private TextView textA = null;
private TextView textA2 = null;
private EditText editA2 = null;
private Button buttonAB = null;
private Button buttonAC = null;
private Button buttonAD = null;
private Button buttonCancel = null;
private Button buttonOK = null;
private EditText dialog_fornavn = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
dialogKnapp = (Button) findViewById(R.id.dialog_knapp);
buttonCancel = (Button) findViewById(R.id.buttonCancel);
buttonOK = (Button) findViewById(R.id.buttonOK);
dialog_fornavn = (EditText) findViewById(R.id.dialog_fornavn);
textA = (TextView) findViewById(R.id.textA);
textA2 = (TextView) findViewById(R.id.textA2);
editA2 = (EditText) findViewById(R.id.editA2);
buttonAB = (Button) findViewById(R.id.buttonAB);
buttonAC = (Button) findViewById(R.id.buttonAC);
buttonAD = (Button) findViewById(R.id.buttonAD);
Intent intent = getIntent();
String navn = intent.getStringExtra("navnet");
textA2.setText(navn);
buttonAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAB();
}
});
buttonAC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAC();
}
});
buttonAD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAD();
}
});
dialogKnapp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startDialog();
}
});
}
private void startAB() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void startAC() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityC.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void startAD() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityD.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void startDialog() {
BasicDialogFragment bdf = new BasicDialogFragment();
bdf.show(getFragmentManager(), "basic");
}
public void OnFragmentInteractionListener(String nameEntered){
visTekst();
}
private void visTekst() {
if(buttonOK.isPressed()){
textA2.setText(dialog_fornavn.getText());
Toast melding = Toast.makeText(getApplicationContext(),
dialog_fornavn.getText(), Toast.LENGTH_SHORT);
melding.show();
} else if(buttonCancel.isPressed()){
startAB();
}
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
Toast toast = Toast.makeText(getApplicationContext(), "Activity A",
Toast.LENGTH_SHORT);
switch (item.getItemId()) {
case R.id.menu_item_1:
toast.setText("Activity A");
toast.show();
return true;
case R.id.menu_item_2:
toast.setText("Activity B");
toast.show();
startAB();
return true;
case R.id.menu_item_3:
toast.setText("Activity C");
toast.show();
startAC();
return true;
case R.id.menu_item_4:
toast.setText("Activity D");
toast.show();
startAD();
return true;
case R.id.action_settings:
toast.setText("Settings");
toast.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
BasicDialogFragment.java
import android.app.Activity;
import android.app.DialogFragment;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link BasicDialogFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link BasicDialogFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class BasicDialogFragment extends DialogFragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnNameEnteredListener {
public void OnFragmentInteractionListener(String nameEntered);
}
private OnNameEnteredListener mListener;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment BasicDialogFragment.
*/
// TODO: Rename and change types and number of parameters
public static BasicDialogFragment newInstance(String param1, String param2) {
BasicDialogFragment fragment = new BasicDialogFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
public BasicDialogFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_basic_dialog, container, false);
this.getDialog().setTitle("First Name");
return v;
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.OnFragmentInteractionListener("uri");
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnNameEnteredListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
fragment_basic_dialog.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" tools:context="no.hit.kvisli.heiverden.BasicDialogFragment"
android:layout_width="match_parent" android:layout_height="match_parent"
android:padding="10dp" android:orientation="vertical" >
<EditText
android:id="#+id/dialog_fornavn"
android:layout_width="match_parent" android:layout_height="wrap_content"
android:textSize="24dp" android:textColor="#android:color/holo_red_dark"
android:hint="Skriv fornavn her" android:inputType="textPersonName" />
<LinearLayout
android:layout_width="match_parent" android:layout_height="wrap_content"
android:padding="10dp" android:orientation="horizontal" >
<Button
android:id="#+id/buttonCancel" android:text="Cancel"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
<Button
android:id="#+id/buttonOK" android:text="OK"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
activity_a.xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true">
<LinearLayout
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/farge_A"
tools:context=".ActivityA">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity A"
android:id="#+id/textA"
style="#style/Overskrift"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textA2"
style="#style/Overskrift"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editA2"
style="#style/EditTekst"
android:hint="Skriv noe her"
android:layout_marginLeft="120dp"
android:layout_marginTop="50dp"/>
<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:orientation="horizontal"
android:layout_marginTop="150dp"
android:layout_marginLeft="50dp"
tools:context=".ActivityA">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dialog"
android:id="#+id/dialog_knapp"
android:background="#color/dialog_knapp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to B"
android:id="#+id/buttonAB"
android:background="#color/farge_B"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to C"
android:id="#+id/buttonAC"
android:background="#color/farge_C"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to D"
android:id="#+id/buttonAD"
android:background="#color/farge_D"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
If I am reading it correctly and your BasicDialogFragment code is like this
then all you need to do is add
public void OnNameEntered(String nameEntered){
//Do Something Here
}
to your ActivityA.java
EDIT
modify the following functions as follows:
private void visTekst(String nameEntered) {
if(buttonOK.isPressed()){
textA2.setText(nameEntered);
Toast melding = Toast.makeText(getApplicationContext(),
dialog_fornavn.getText(), Toast.LENGTH_SHORT);
melding.show();
} else if(buttonCancel.isPressed()){
startAB();
}
}
and call it as
public void OnFragmentInteractionListener(String nameEntered){
visTekst(nameEntered);
}
You need to setup your listeners as it is mentioned in the code that you have used
in your BasicDialogFragment
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_basic_dialog, container, false);
this.getDialog().setTitle("First Name");
buttonCancel = (Button) findViewById(R.id.buttonCancel);
buttonOK = (Button) findViewById(R.id.buttonOK);
buttonCancel.setOnClickListner(new View.OnClickListener(View v){
onButtonPressed(/*Your custom URI*/Uri uri);
});
buttonOK .setOnClickListner(new View.OnClickListener(View v){
onButtonPressed(/*Your custom URI*/Uri uri);
});
return v;
}
For this issue, there are two ways, one is direct cast to hosted Activity to get activity instance. Another is using one interface that defined in DialogFragment but implemented by hosted Activity.
For detail please follow my previous post Call activity from DialogFragment.
//Here is the answer. Took a while but got it to the end, thanks for your help.
//ActivityA
import android.app.FragmentManager;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class ActivityA extends ActionBarActivity implements BasicDialogFragment.Communicator {
private Button dialogKnapp = null;
private TextView textA = null;
private TextView textA2 = null;
private EditText editA2 = null;
private Button buttonAB = null;
private Button buttonAC = null;
private Button buttonAD = null;
private EditText dialog_fornavn = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
dialogKnapp = (Button) findViewById(R.id.dialog_knapp);
dialog_fornavn = (EditText) findViewById(R.id.dialog_fornavn);
textA = (TextView) findViewById(R.id.textA);
textA2 = (TextView) findViewById(R.id.textA2);
editA2 = (EditText) findViewById(R.id.editA2);
buttonAB = (Button) findViewById(R.id.buttonAB);
buttonAC = (Button) findViewById(R.id.buttonAC);
buttonAD = (Button) findViewById(R.id.buttonAD);
Intent intent = getIntent();
String navn = intent.getStringExtra("navnet");
textA2.setText(navn);
buttonAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAB();
}
});
buttonAC.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAC();
}
});
buttonAD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startAD();
}
});
dialogKnapp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startDialog();
}
});
}
private void startAB() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void startAC() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityC.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
private void startAD() {
String navn = editA2.getText().toString().toUpperCase();
Intent intent = new Intent(ActivityA.this, ActivityD.class);
intent.putExtra("navnet", navn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
public void startDialog(){
FragmentManager manager = getFragmentManager();
BasicDialogFragment basicDialogFragment = new BasicDialogFragment();
basicDialogFragment.show(manager,"BasicDialogFragment");
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
Toast toast = Toast.makeText(getApplicationContext(), "Activity A",
Toast.LENGTH_SHORT);
switch (item.getItemId()) {
case R.id.menu_item_1:
toast.setText("Activity A");
toast.show();
return true;
case R.id.menu_item_2:
toast.setText("Activity B");
toast.show();
startAB();
return true;
case R.id.menu_item_3:
toast.setText("Activity C");
toast.show();
startAC();
return true;
case R.id.menu_item_4:
toast.setText("Activity D");
toast.show();
startAD();
return true;
case R.id.action_settings:
toast.setText("Settings");
toast.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onDialogMessage(Editable message) {
textA2.setText(message);
}
}
//BasicDialogFragment
`import android.app.Activity;
import android.app.DialogFragment;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class BasicDialogFragment extends DialogFragment implements View.OnClickListener{
private Button buttonCancel = null;
private Button buttonOK = null;
private EditText dialog_fornavn = null;
Communicator communicator;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
communicator= (Communicator) activity;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_basic_dialog, null);
buttonCancel = (Button) v.findViewById(R.id.buttonCancel);
buttonOK = (Button) v.findViewById(R.id.buttonOK);
dialog_fornavn = (EditText) v.findViewById(R.id.dialog_fornavn);
buttonCancel.setOnClickListener(this);
buttonOK.setOnClickListener(this);
setCancelable(true);
return v;
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.buttonOK){
communicator.onDialogMessage(dialog_fornavn.getText());
dismiss();
}
else{
dismiss();
}
}
interface Communicator{
public void onDialogMessage(Editable message);
}
}`
//Thats it, nothing chaged in xml files. Not sure if its good coding but worked for me.