Cant run another activity from a FragmentActivity.! - android

I have an activity with a ViewPager containing 3 fragments.
Each fragment is to hold a listview, and I wish to start a new activity when a list item is clicked.
I am unable to run the startActivity() method from the onItemClickListener. Help!
BTListDevice.java
package com.example.pager;
import java.util.Set;
import android.support.v4.app.Fragment;
import android.app.Activity;
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.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class BTListDevice extends FragmentActivity {
// Fragments
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
// Debugging
private static final String TAG = "BluetoothChat";
private static final boolean D = true;
// Message types sent from the BluetoothChatService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
// Intent request codes
private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
// Return Intent extra
public static String DEVICE_DET = "dev";
private static final int REQUEST_ENABLE_BT = 7;
// Member fields
private static BluetoothAdapter mBtAdapter;
private static DevicesCursor devicesAdapter;
private static ChatDBHelper dbHelper;
private static ListView pairedListView;
private ListView newDevicesListView;
private static ListView homeList;
private static HomeListAdapter iAdap;
boolean buttonState;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get Default Adapter for the device
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
dbHelper = new ChatDBHelper(this);
if (mBtAdapter.isEnabled())
buttonState=true;
else
buttonState=false;
invalidateOptionsMenu();
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_navigator);
// Create the adapter that will return a fragment for each of the three primary sections
// of the app.
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setCurrentItem(1);
// Set result CANCELED in case the user backs out
setResult(Activity.RESULT_CANCELED);
}
#Override
protected void onResume() {
super.onResume();
if (mBtAdapter.isEnabled())
buttonState=true;
else
buttonState=false;
invalidateOptionsMenu();
}
#Override
protected void onDestroy() {
super.onDestroy();
// Make sure we're not doing discovery anymore
if (mBtAdapter != null) {
mBtAdapter.cancelDiscovery();
}
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.home_screen_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch(item.getItemId()) {
case R.id.menu_BT :
{
if (!mBtAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
//Toast.makeText(getApplicationContext(), "Enabling Bluetooth..", Toast.LENGTH_SHORT).show();
}
else {
if (mBtAdapter.isEnabled()) {
mBtAdapter.disable();
buttonState=false;
invalidateOptionsMenu();
//Toast.makeText(getApplicationContext(), "Disabling Bluetooth..", Toast.LENGTH_SHORT).show();
}
}
}
return true;
default :
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem BT = menu.findItem(R.id.menu_BT);
if(buttonState)
{
BT.setIcon(R.drawable.bt_on);
return true;
}
else
BT.setIcon(R.drawable.bt_off);
return super.onPrepareOptionsMenu(menu);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
switch(requestCode)
{
case REQUEST_ENABLE_BT : {
if(resultCode==RESULT_OK)
{
buttonState=true;
invalidateOptionsMenu();
// Get a set of currently paired devices
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
String text = String.valueOf(pairedDevices.size());
Toast.makeText(getApplicationContext(),text, Toast.LENGTH_SHORT).show();
if (pairedDevices.size() > 0)
{
dbHelper.DTdelAllData();
for (BluetoothDevice device : pairedDevices)
{
dbHelper.DTinsertData(device.getAddress(), device.getName());
}
}
}
else
{
buttonState=false;
invalidateOptionsMenu();
}
}
break;
}
}
public void searchForDevices(View v)
{
if (mBtAdapter == null) {
Toast.makeText(getApplicationContext(), "Device not supported!", Toast.LENGTH_LONG).show();
return;
}
else
{
if (!mBtAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
//Toast.makeText(getApplicationContext(), "Enabling Bluetooth..", Toast.LENGTH_LONG).show();
}
else
{
doDiscovery();
v.setVisibility(View.GONE);
}
}
}
private void doDiscovery() {
//if (D) Log.d(TAG, "doDiscovery()");
// Indicate scanning in the title
setProgressBarIndeterminateVisibility(true);
setTitle("Scanning");
// If we're already discovering, stop it
if (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBtAdapter.startDiscovery();
}
// The on-click listener for all devices in the ListViews
static OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mBtAdapter.cancelDiscovery();
Cursor c = dbHelper.DTgetAllData();
c.moveToPosition(arg2);
String device = c.getString(0);
// Create the result Intent and include the MAC address
Intent intent = new Intent(BTListDevice.this,ChatActivity.class);
intent.putExtra(DEVICE_DET, device);
// Set result and finish this Activity
BTListDevice.this.startActivity(intent);
}
};
public class AppSectionsPagerAdapter extends FragmentPagerAdapter {
Fragment frag;
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0 :
frag = new PairedDevicesFragment();
break;
case 2 :
frag = new NewDevicesFragment();
break;
case 1 :
frag = new HomeScreenFragment();
break;
default :
frag = new HomeScreenFragment();
}
return frag;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
String title = null;
switch(position)
{
case 0 : title = "Paired Devices";
break;
case 1 : title = "Chats";
break;
case 2 : title = "New Devices";
break;
}
return (CharSequence)title;
}
}
public static class PairedDevicesFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.paired_devices, container, false);
// Find and set up the ListView for paired devices
pairedListView = (ListView) rootView.findViewById(R.id.paired_devices);
pairedListView.setOnItemClickListener(mDeviceClickListener);
new Handler().post(new Runnable() {
#Override
public void run() {
devicesAdapter = new DevicesCursor(getActivity().getApplicationContext(), dbHelper.DTgetAllData());
pairedListView.setAdapter(devicesAdapter);
}
});
return rootView;
}
}
public static class NewDevicesFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.new_devices, container, false);
// Find and set up the ListView for paired devices
pairedListView = (ListView) rootView.findViewById(R.id.new_devices);
pairedListView.setOnItemClickListener(BTListDevice.mDeviceClickListener);
return rootView;
}
}
public static class HomeScreenFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.home_screen, container, false);
homeList = (ListView)rootView.findViewById(android.R.id.list);
Cursor cur = dbHelper.CTgetChatDevices();
cur.moveToFirst();
if(cur.getCount()>0)
{
new Handler().post(new Runnable() {
#Override
public void run() {
iAdap = new HomeListAdapter(getActivity().getApplicationContext());
homeList.setAdapter(iAdap);
}
});
}
else
{
TextView empty = (TextView)rootView.findViewById(android.R.id.empty);
empty.setText("There is No Cheese!");
empty.setVisibility(View.VISIBLE);
homeList.setVisibility(View.GONE);
}
return rootView;
}
}
}
EDIT :
When i try to call startActivity(), I get this error in onItemClickListener.
Cannot make a static reference to the non-static method startActivity(Intent) from the type Activity.

Just Change the code for each fragment
public static class PairedDevicesFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.paired_devices, container, false);
// Find and set up the ListView for paired devices
pairedListView = (ListView) rootView.findViewById(R.id.paired_devices);
pairedListView.setOnItemClickListener(mDeviceClickListener);
new Handler().post(new Runnable() {
#Override
public void run() {
devicesAdapter = new DevicesCursor(getActivity().getApplicationContext(), dbHelper.DTgetAllData());
pairedListView.setAdapter(devicesAdapter);
}
});
pairedListView .setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Cursor c = dbHelper.DTgetAllData();
c.moveToPosition(arg2);
String device = c.getString(0);
// Create the result Intent and include the MAC address
Intent intent = new Intent(getActivity(),ChatActivity.class);
intent.putExtra(DEVICE_DET, device);
// Set result and finish this Activity
getActivity().startActivity(intent);
}
});
return rootView;
}
}

Give this a try,
Instead of doing it this way, getActivity().startActivity(intent);
try this,
BTListDevice.this.startActivity(intent);

Change the onItemClick Code as following
static OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mBtAdapter.cancelDiscovery();
Cursor c = dbHelper.DTgetAllData();
c.moveToPosition(arg2);
String device = c.getString(0);
// Create the result Intent and include the MAC address
Intent intent = new Intent(getActivity(),ChatActivity.class);
intent.putExtra(DEVICE_DET, device);
// Set result and finish this Activity
getActivity().startActivity(intent);
}
};

Try this fragment of code
// Create the result Intent and include the MAC address
Intent intent = new Intent(getActivity(), ChatActivity.class);
intent.putExtra(DEVICE_DET, device);
// Set result and finish this Activity
startActivity(intent);

Related

error: unreachable statement myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

I am creating an application for working with a bluetooth device using the navigation drawer activity template, there was a problem with initializing the bluetooth adapter in a fragment, I attach my code below. When compiling the code, it gives the error
error: unreachable statement
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
package com.example.myt.ui.home;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.ui.AppBarConfiguration;
import com.example.myt.R;
import java.io.IOException;
import java.util.Set;
import java.util.UUID;
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
private static final int REQUEST_ENABLE_BT = 1;
private Button onBtn;
private Button offBtn;
private Button listBtn;
private Button findBtn;
private TextView text;
private BluetoothAdapter myBluetoothAdapter;
private BluetoothSocket socket;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private AppBarConfiguration mAppBarConfiguration;
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
homeViewModel =
ViewModelProviders.of(this).get(HomeViewModel.class);
View root = inflater.inflate(R.layout.fragment_home, container, false);
return root;
// take an instance of BluetoothAdapter - Bluetooth radio
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter == null) {
onBtn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getActivity().getBaseContext(),"Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
text = (TextView) root.findViewById(R.id.text);
onBtn = (Button) root.findViewById(R.id.turnOn);
onBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
on(v);
}
});
offBtn = (Button) root.findViewById(R.id.turnOff);
offBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
off(v);
}
});
listBtn = (Button) root.findViewById(R.id.paired);
listBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
});
findBtn = (Button) root.findViewById(R.id.search);
findBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView) root.findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
}
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
myBluetoothAdapter.cancelDiscovery();
final String info = ((TextView) arg1).getText().toString();
//get the device address when click the device item
String address = info.substring(info.length()-17);
//connect the device when item is click
BluetoothDevice connect_device = myBluetoothAdapter.getRemoteDevice(address);
try {
socket = connect_device.createRfcommSocketToServiceRecord(MY_UUID);
socket.connect();
} catch (IOException e) {
try {
socket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
}
});//************new_devices_list end
}
private void errorExit(String title, String message){
Toast.makeText(getActivity().getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
getActivity().finish();
}
public void on(View view){
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Toast.makeText(getActivity().getBaseContext(),"Bluetooth turned on" ,
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getActivity().getBaseContext(),"Bluetooth is already on",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BT) {
if (myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");
}
}
}
public void list(View view){
// get paired devices
pairedDevices = myBluetoothAdapter.getBondedDevices();
// put it's one to the adapter
for(BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());
Toast.makeText(getActivity().getBaseContext(),"Show Paired Devices",
Toast.LENGTH_SHORT).show();
}
final BroadcastReceiver bReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// add the name and the MAC address of the object to the arrayAdapter
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
getActivity().registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
public void off(View view){
myBluetoothAdapter.disable();
text.setText("Status: Disconnected");
Toast.makeText(getActivity().getBaseContext(),"Bluetooth turned off",
Toast.LENGTH_LONG).show();
}
}
You are returning the view immediately on onCreateView, which is why the rest of the code can never be reached. The issue is here:
View root = inflater.inflate(R.layout.fragment_home, container, false);
return root;
Place return root; after:
new_devices list end

Did not get BLE (Bluetooth Low Engery) scanned device on callback in Android?

we used google sample code for getting BLE scanned devices. here is link enter link description here.
Below is scanLeDevice method and mLeScanCallback callback method
package com.example.android.bluetoothlegatt;
import android.app.Activity;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
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 LeDeviceListAdapter mLeDeviceListAdapter;
private BluetoothAdapter mBluetoothAdapter;
private boolean mScanning;
private Handler mHandler;
private static final int REQUEST_ENABLE_BT = 1;
private static final int REQUEST_DISCOVERABLE = 2;
// Stops scanning after 10 seconds.
private static final long SCAN_PERIOD = 1000000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setTitle(R.string.title_devices);
mHandler = new Handler();
// 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;
}
if (!mBluetoothAdapter.isEnabled()) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
makeDiscoverable();
}
#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;
}
private void makeDiscoverable() {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 30000);
startActivity(discoverableIntent);
Log.i("Log", "Discoverable ");
}
#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()) {
// if (!mBluetoothAdapter.isEnabled()) {
// Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
// startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
// makeDiscoverable();
// }
// }
// 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();
if (deviceName != null && deviceName.length() > 0)
viewHolder.deviceName.setText(deviceName);
else
viewHolder.deviceName.setText(R.string.unknown_device);
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;
}
}
Can anyone know what is issue or does any other setting require in code for get working?

Loading data from sqlite and displaying on ViewPager

Been trying to load data from sqlite and display it on viewpager without much success.
I have a viewpager with two tabs which should hold data based on the tag_id passed as a parameter of newInstance. There is also an action bar navigation spinner with a list of counties that is used for filter data displayed based on the county_id.
Am able to fetch data from server and save it in the sqlite db but displaying it is the problem. Data is not dispalyed on the first page of the viewpager but it exists in the sqlite. Data for the second is the only one laoded.
Below is my implementation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.OnNavigationListener;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.app.adapter.CustomCountySpinnerAdapter;
import com.app.adapter.TendersAdapter;
import com.app.database.DBFunctions;
import com.app.externallib.AppController;
import com.app.model.CountyModel;
import com.app.model.PostsModel;
import com.app.utils.AppConstants;
import com.app.utils.PostsListLoader;
import com.nhaarman.listviewanimations.appearance.simple.SwingBottomInAnimationAdapter;
import com.viewpagerindicator.TabPageIndicator;
public class PublicTendersFragment extends Fragment{
private static List<PubliTenders> public_tenders;
public PublicTendersFragment newInstance(String text) {
PublicTendersFragment mFragment = new PublicTendersFragment();
Bundle mBundle = new Bundle();
mBundle.putString(AppConstants.TEXT_FRAGMENT, text);
mFragment.setArguments(mBundle);
return mFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
public_tenders = new ArrayList<PubliTenders>();
public_tenders.add(new PubliTenders(14, "County"));
public_tenders.add(new PubliTenders(15, "National"));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final Context contextThemeWrapper = new ContextThemeWrapper(
getActivity(), R.style.StyledIndicators);
LayoutInflater localInflater = inflater
.cloneInContext(contextThemeWrapper);
View v = localInflater.inflate(R.layout.fragment_tenders, container,
false);
FragmentPagerAdapter adapter = new TendersVPAdapter(
getFragmentManager());
ViewPager pager = (ViewPager) v.findViewById(R.id.pager);
pager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator) v
.findViewById(R.id.indicator);
indicator.setViewPager(pager);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
class TendersVPAdapter extends FragmentPagerAdapter{
public TendersVPAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Parcelable saveState() {
return null;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return Tenders.newInstance(public_tenders.get(position).tag_id);
case 1:
return Tenders.newInstance(public_tenders.get(position).tag_id);
default:
return null;
}
}
#Override
public CharSequence getPageTitle(int position) {
return public_tenders.get(position).tender_type.toUpperCase(Locale
.getDefault());
}
#Override
public int getCount() {
return public_tenders.size();
}
}
public class PubliTenders {
public int tag_id;
public String tender_type;
public PubliTenders(int tag_id, String tender_type) {
this.tag_id = tag_id;
this.tender_type = tender_type;
}
}
public static class Tenders extends ListFragment implements
OnNavigationListener, LoaderCallbacks<ArrayList<PostsModel>> {
boolean mDualPane;
int mCurCheckPosition = 0;
// private static View rootView;
private SwipeRefreshLayout swipeContainer;
private ListView lv;
private View rootView;
private DBFunctions mapper;
private CustomCountySpinnerAdapter spinadapter;
private TendersAdapter mTendersAdapter;
private static final String ARG_TAG_ID = "tag_id";
private int tag_id;
private int mycounty;
private static final int INITIAL_DELAY_MILLIS = 500;
private static final String DEBUG_TAG = "BlogsFragment";
private final String TAG_REQUEST = "BLOG_TAG";
private JsonArrayRequest jsonArrTendersRequest;
// private OnItemSelectedListener listener;
public static Tenders newInstance(int tag_id) {
Tenders fragment = new Tenders();
Bundle b = new Bundle();
b.putInt(ARG_TAG_ID, tag_id);
fragment.setArguments(b);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tag_id = getArguments().getInt(ARG_TAG_ID);
}
#Override
public void onStart() {
super.onStart();
getLoaderManager().initLoader(0, null, this);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_headlines_blog,
container, false);
swipeContainer = (SwipeRefreshLayout) rootView
.findViewById(R.id.swipeProjectsContainer);
lv = (ListView) rootView.findViewById(android.R.id.list);
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view,
int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
int topRowVerticalPosition = (lv == null || lv
.getChildCount() == 0) ? 0 : lv.getChildAt(0)
.getTop();
swipeContainer.setEnabled(topRowVerticalPosition >= 0);
}
});
swipeContainer.setOnRefreshListener(new OnRefreshListener() {
#Override
public void onRefresh() {
fetchPublicTenders(mycounty);
}
});
swipeContainer.setColorSchemeResources(R.color.blue_dark,
R.color.irdac_green, R.color.red_light,
R.color.holo_red_light);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
mapper = new DBFunctions(getActivity());
mapper.open();
// initialize AB Spinner
populateSpinner();
fetchPublicTenders(mycounty);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
private void populateSpinner() {
try {
List<CountyModel> counties = new ArrayList<CountyModel>();
counties = mapper.getAllCounties();
ActionBar actBar = ((ActionBarActivity) getActivity())
.getSupportActionBar();
actBar.setDisplayShowTitleEnabled(true);
actBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
spinadapter = new CustomCountySpinnerAdapter(getActivity(),
android.R.layout.simple_spinner_dropdown_item, counties);
actBar.setListNavigationCallbacks(spinadapter, this);
} catch (NullPointerException exp) {
}
}
#Override
public Loader<ArrayList<PostsModel>> onCreateLoader(int arg0,
Bundle arg1) {
Log.v(DEBUG_TAG, "On Create Loader");
return new PostsListLoader(getActivity(), mycounty, tag_id);
}
#Override
public void onLoadFinished(Loader<ArrayList<PostsModel>> arg0,
ArrayList<PostsModel> data) {
// System.out.println("results " + data.size());
addToAdapter(data);
}
#Override
public void onLoaderReset(Loader<ArrayList<PostsModel>> arg0) {
lv.setAdapter(null);
}
#Override
public boolean onNavigationItemSelected(int pos, long arg1) {
CountyModel mo = spinadapter.getItem(pos);
this.mycounty = mo.getId();
refresh(mo.getId());
return false;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
TextView txtTitle = (TextView) v.findViewById(R.id.tender_title);
TextView txtRefNo = (TextView) v.findViewById(R.id.ref_no);
TextView txtExpiryDate = (TextView) v
.findViewById(R.id.expiry_date);
TextView txtOrg = (TextView) v.findViewById(R.id.dept_or_org);
Intent intTenderFullDetails = new Intent(getActivity(),
TenderDetailsActivity.class);
intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_TITLE,
txtTitle.getText().toString().trim());
intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_REF_NO,
txtRefNo.getText().toString().trim());
intTenderFullDetails.putExtra(
TenderDetailsActivity.TENDER_EXPIRY_DATE, txtExpiryDate
.getText().toString().trim());
intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_ORG,
txtOrg.getText().toString().trim());
// intTenderFullDetails.putExtra(TenderDetailsActivity.TENDER_DESC,
// Lorem);
startActivity(intTenderFullDetails);
}
private void fetchPublicTenders(final int county_id) {
swipeContainer.setRefreshing(true);
Uri.Builder builder = Uri.parse(AppConstants.postsUrl).buildUpon();
builder.appendQueryParameter("tag_id", Integer.toString(tag_id));
System.out.println("fetchPublicTenders with tag_id " + tag_id
+ " and county_id " + county_id);
jsonArrTendersRequest = new JsonArrayRequest(builder.toString(),
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
if (response.length() > 0) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject tender_item = response
.getJSONObject(i);
mapper.createPost(
tender_item.getInt("id"),
tender_item.getInt("tag_id"),
tender_item.getInt("county_id"),
tender_item.getInt("sector_id"),
tender_item.getString("title"),
tender_item.getString("slug"),
tender_item.getString("content"),
tender_item
.getString("reference_no"),
tender_item
.getString("expiry_date"),
tender_item
.getString("organization"),
tender_item
.getString("image_url"),
tender_item
.getString("created_at"));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
swipeContainer.setRefreshing(false);
refresh(county_id);
}
} else {
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
try {
Toast.makeText(getActivity(),
"Sorry! No results found",
Toast.LENGTH_LONG).show();
} catch (NullPointerException npe) {
System.out.println(npe);
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
if (error instanceof NetworkError) {
try {
Toast.makeText(
getActivity(),
"Network Error. Cannot refresh list",
Toast.LENGTH_SHORT).show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
refresh(county_id);
} else if (error instanceof ServerError) {
try {
Toast.makeText(
getActivity(),
"Problem Connecting to Server. Try Again Later",
Toast.LENGTH_SHORT).show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ParseError) {
} else if (error instanceof NoConnectionError) {
try {
Toast.makeText(getActivity(),
"No Connection", Toast.LENGTH_SHORT)
.show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
} else if (error instanceof TimeoutError) {
try {
Toast.makeText(
getActivity()
.getApplicationContext(),
"Timeout Error. Try Again Later",
Toast.LENGTH_SHORT).show();
} catch (NullPointerException npe) {
System.err.println(npe);
}
}
if (swipeContainer.isShown()) {
swipeContainer.setRefreshing(false);
}
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
return headers;
}
};
// Set a retry policy in case of SocketTimeout & ConnectionTimeout
// Exceptions. Volley does retry for you if you have specified the
// policy.
jsonArrTendersRequest.setRetryPolicy(new DefaultRetryPolicy(
(int) TimeUnit.SECONDS.toMillis(20),
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
jsonArrTendersRequest.setTag(TAG_REQUEST);
AppController.getInstance().addToRequestQueue(jsonArrTendersRequest);
}
public void refresh(int county_id) {
Bundle b = new Bundle();
b.putInt("myconty", county_id);
if (isAdded()) {
getLoaderManager().restartLoader(0, b, this);
}
}
private void addToAdapter(ArrayList<PostsModel> plist) {
mTendersAdapter = new TendersAdapter(rootView.getContext(), plist);
SwingBottomInAnimationAdapter swingBottomInAnimationAdapter = new SwingBottomInAnimationAdapter(
mTendersAdapter);
swingBottomInAnimationAdapter.setAbsListView(lv);
assert swingBottomInAnimationAdapter.getViewAnimator() != null;
swingBottomInAnimationAdapter.getViewAnimator()
.setInitialDelayMillis(INITIAL_DELAY_MILLIS);
setListAdapter(swingBottomInAnimationAdapter);
mTendersAdapter.notifyDataSetChanged();
}
}
}
And this is the PostsListLoader class
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.support.v4.content.AsyncTaskLoader;
import com.app.database.DBFunctions;
import com.app.model.PostsModel;
public class PostsListLoader extends AsyncTaskLoader<ArrayList<PostsModel>> {
private DBFunctions mapper;
private ArrayList<PostsModel> myPostsModel;
private int county_id;
private int tag_id;
public PostsListLoader(Context context, int county_id, int tag_id) {
super(context);
mapper = new DBFunctions(getContext());
mapper.open();
this.county_id = county_id;
this.tag_id = tag_id;
}
#Override
public ArrayList<PostsModel> loadInBackground() {
String query_string = AppConstants.KEY_COUNTY_ID + " = " + county_id
+ " AND " + AppConstants.KEY_TAG_ID + " = " + tag_id;
myPostsModel = mapper.getPosts(query_string);
return myPostsModel;
}
#Override
public void deliverResult(ArrayList<PostsModel> data) {
if (isReset()) {
// An async query came in while the loader is stopped. We
// don't need the result.
if (data != null) {
onReleaseResources(data);
}
}
List<PostsModel> oldNews = data;
myPostsModel = data;
if (isStarted()) {
// If the Loader is currently started, we can immediately
// deliver its results.
super.deliverResult(data);
}
// At this point we can release the resources associated with
// 'oldNews' if needed; now that the new result is delivered we
// know that it is no longer in use.
if (oldNews != null) {
onReleaseResources(oldNews);
}
}
/**
* Handles a request to start the Loader.
*/
#Override
protected void onStartLoading() {
if (myPostsModel != null) {
// If we currently have a result available, deliver it
// immediately.
deliverResult(myPostsModel);
}
if (takeContentChanged() || myPostsModel == null) {
// If the data has changed since the last time it was loaded
// or is not currently available, start a load.
forceLoad();
}
}
/**
* Handles a request to stop the Loader.
*/
#Override
protected void onStopLoading() {
// Attempt to cancel the current load task if possible.
cancelLoad();
}
/**
* Handles a request to cancel a load.
*/
#Override
public void onCanceled(ArrayList<PostsModel> news) {
super.onCanceled(news);
// At this point we can release the resources associated with 'news'
// if needed.
onReleaseResources(news);
}
/**
* Handles a request to completely reset the Loader.
*/
#Override
protected void onReset() {
super.onReset();
// Ensure the loader is stopped
onStopLoading();
// At this point we can release the resources associated with 'apps'
// if needed.
if (myPostsModel != null) {
onReleaseResources(myPostsModel);
myPostsModel = null;
}
}
/**
* Helper function to take care of releasing resources associated with an
* actively loaded data set.
*/
protected void onReleaseResources(List<PostsModel> news) {
}
}
What could I be doing wrong?
Any help will be appreciated.
Thanks

Regarding migrating searchview on appcompat

I am migrating search view Item provided in action bar using support library .Here I have done as mentioned in doc but still it is giving error while creating options menu.Please tell me where I have done wrong.Here is my code.
contacts_list_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:com.utteru.ui="http://schemas.android.com/apk/res-auto"
xmlns:yourapp="http://schemas.android.com/tools">
<!-- The search menu item. Honeycomb and above uses an ActionView or specifically a SearchView
which expands within the Action Bar directly. Note the initial collapsed state set using
collapseActionView in the showAsAction attribute. -->
<group
android:id="#+id/main_menu_group">
<item
android:id="#+id/menu_search"
android:actionViewClass="android.widget.SearchView"
android:icon="#drawable/ic_action_search"
yourapp:showAsAction="ifRoom|collapseActionView"
yourapp:actionViewClass="android.support.v7.widget.SearchView"
android:title="#string/menu_search" />
</group>
<group
android:id="#+id/refresh_group">
<item
android:id="#+id/refresh"
android:icon="#android:drawable/ic_popup_sync"
yourapp:showAsAction="ifRoom|collapseActionView"
yourapp:actionViewClass="android.support.v7.widget.SearchView"
android:title="#string/menu_search" />
</group>
</menu>
ContactsListFragment.java
import android.accounts.Account;
import android.app.SearchManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Contacts.Photo;
import android.support.v4.BuildConfig;
import android.support.v4.app.ListFragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
public class ContactsListFragment extends ListFragment {
private static final String TAG = "ContactsAccessFragment";
private static final String STATE_PREVIOUSLY_SELECTED_KEY =
"com.Utteru.ui.SELECTED_ITEM";
ArrayList<AccessContactDto> allcontacts;
ArrayList<AccessContactDto> databasecontacts;
TextView textempty;
public Context mContext;
private AccessContactAdapter mAdapter;
private ImageLoader mImageLoader; // Handles loading the contact image in a background thread
// Stores the previously selected search item so that on a configuration change the same item
// can be reselected again
private int mPreviouslySelectedSearchItem = 0;
// Whether or not the search query has changed since the last time the loader was refreshed
private boolean mSearchQueryChanged;
// Whether or not this fragment is showing in a two-pane layout
private boolean mIsTwoPaneLayout;
// Whether or not this is a search result view of this fragment, only used on pre-honeycomb
// OS versions as search results are shown in-line via Action Bar search from honeycomb onward
private boolean mIsSearchResultView = false;
/**
* Fragments require an empty constructor.
*/
public ContactsListFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mIsTwoPaneLayout = getResources().getBoolean(R.bool.has_two_panes);
getActivity().setTitle("");
if (savedInstanceState != null) {
// If we're restoring state after this fragment was recreated then
// retrieve previous search term and previously selected search
// result.
mPreviouslySelectedSearchItem =
savedInstanceState.getInt(STATE_PREVIOUSLY_SELECTED_KEY, 0);
}
mImageLoader = new ImageLoader(getActivity(), CommonUtility.getListPreferredItemHeight(getActivity())) {
#Override
protected Bitmap processBitmap(Object data) {
// This gets called in a background thread and passed the data from
// ImageLoader.loadImage().
return loadContactPhotoThumbnail((String) data, getImageSize());
}
};
// Set a placeholder loading image for the image loader
mImageLoader.setLoadingImage(R.drawable.ic_contact_picture_holo_light);
// Add a cache to the image loader
mImageLoader.addImageCache(getActivity().getSupportFragmentManager(), 0.1f);
mContext = getActivity().getBaseContext();
new loadData().execute();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the list fragment layout
View all_contacts_view = inflater.inflate(R.layout.contact_list_fragment, container, false);
textempty = (TextView)all_contacts_view.findViewById(android.R.id.empty);
textempty.setText("No contacts found");
return all_contacts_view;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
AccessContactDto cdto = (AccessContactDto) l.getItemAtPosition(position);
Log.e("number on click",""+cdto.getMobile_number());
cdto=UserService.getUserServiceInstance(mContext).getAccessConDataByNumber(cdto.getMobile_number());
if(cdto==null)
cdto = (AccessContactDto) l.getItemAtPosition(position);
else
Log.e("mumber not mull from db","number not null from db");
Intent detailsActivity = new Intent(mContext, ContactDetailActivity.class);
detailsActivity.putExtra("selected_con", cdto);
startActivity(detailsActivity);
getActivity().overridePendingTransition(R.anim.animation1, R.anim.animation2);
super.onListItemClick(l, v, position, id);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Let this fragment contribute menu items
setHasOptionsMenu(true);
// Set up ListView, assign adapter and set some listeners. The adapter was previously
// created in onCreate().
setListAdapter(mAdapter);
getListView().setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
// Pause image loader to ensure smoother scrolling when flinging
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_FLING) {
mImageLoader.setPauseWork(true);
} else {
mImageLoader.setPauseWork(false);
}
}
#Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
}
});
if (mIsTwoPaneLayout) {
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
if (mPreviouslySelectedSearchItem == 0) {
}
}
#Override
public void onPause() {
super.onPause();
mImageLoader.setPauseWork(false);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
menu.clear();
getActivity().getMenuInflater().inflate(R.menu.contact_list_menu, menu);
MenuItem searchItem = menu.findItem(R.id.menu_search);
menu.setGroupVisible(R.id.main_menu_group, true);
if (mIsSearchResultView) {
searchItem.setVisible(false);
}
if (Utils.hasHoneycomb()) {
final SearchManager searchManager =
(SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getActivity().getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String queryText) {
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
Log.e("on query text change ","on query text change");
if (newText != null && !newText.equals(""))
{
ArrayList<AccessContactDto> filterList = new ArrayList<AccessContactDto>();
for (AccessContactDto a : allcontacts) {
if (a.getDisplay_name().toLowerCase().startsWith(newText.toLowerCase())) {
filterList.add(a);
continue;
}
getListView().setAdapter(new AccessContactAdapter(filterList, getActivity(), mImageLoader));
}
return true;
}
else{
getListView().setAdapter(new AccessContactAdapter(allcontacts, getActivity(), mImageLoader));
return true;
}
}
});
}
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_search:
if (!Utils.hasHoneycomb()) {
getActivity().onSearchRequested();
}
break;
case R.id.refresh:
if (CommonUtility.isNetworkAvailable(getActivity())) {
final Account account = new Account(Constants.ACCOUNT_NAME, Constants.ACCOUNT_TYPE);
Bundle bundle = new Bundle();
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
ContentResolver.requestSync(account, ContactsContract.AUTHORITY, bundle);
mAdapter.notifyDataSetChanged();
// new CountDownTimer(5000, 1000) {
// #Override
// public void onTick(long millisUntilFinished) {
// }
//
// #Override
// public void onFinish() {
//
// }
// }.start();
} else {
Toast.makeText(getActivity(), "Internet Connection Required!!", Toast.LENGTH_SHORT).show();
}
break;
}
return super.onOptionsItemSelected(item);
}
private Bitmap loadContactPhotoThumbnail(String photoData, int imageSize) {
if (!isAdded() || getActivity() == null) {
return null;
}
AssetFileDescriptor afd = null;
try {
Uri thumbUri;
if (Utils.hasHoneycomb()) {
thumbUri = Uri.parse(photoData);
} else {
final Uri contactUri = Uri.withAppendedPath(Contacts.CONTENT_URI, photoData);
thumbUri = Uri.withAppendedPath(contactUri, Photo.CONTENT_DIRECTORY);
}
afd = getActivity().getContentResolver().openAssetFileDescriptor(thumbUri, "r");
FileDescriptor fileDescriptor = afd.getFileDescriptor();
if (fileDescriptor != null) {
return ImageLoader.decodeSampledBitmapFromDescriptor(
fileDescriptor, imageSize, imageSize);
}
} catch (FileNotFoundException e) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Contact photo thumbnail not found for contact " + photoData
+ ": " + e.toString());
}
} finally {
if (afd != null) {
try {
afd.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
public ArrayList<AccessContactDto> readContactsNew() {
ArrayList<AccessContactDto> list = new ArrayList<AccessContactDto>();
AccessContactDto adto;
Cursor phones = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String photouri= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));
String contact_id= phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
Uri con_uri= Contacts.getLookupUri(phones.getLong(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID)), phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY)));
adto = new AccessContactDto(contact_id, name, null, phoneNumber, null, photouri, con_uri.toString(),null,null,null);
list.add(adto);
}
phones.close();
return list;
}
public class loadData extends AsyncTask<Void, Void, Void>
{
#Override
protected void onPostExecute(Void aVoid) {
mAdapter = new AccessContactAdapter(allcontacts, getActivity(), mImageLoader);
if(getActivity()!=null)
getListView().setAdapter(mAdapter);
super.onPostExecute(aVoid);
}
#Override
protected Void doInBackground(Void... params) {
allcontacts = readContactsNew();
// databasecontacts = UserService.getUserServiceInstance(mContext).getAllAccessContacts();
// allcontacts.removeAll(databasecontacts);
// allcontacts.addAll(databasecontacts);
Collections.sort(allcontacts, new Comparator<AccessContactDto>() {
#Override
public int compare(AccessContactDto lhs, AccessContactDto rhs) {
return lhs.getDisplay_name().compareToIgnoreCase(rhs.getDisplay_name());
}
});
return null;
}
}
}
ContactsListActivity.java
import android.accounts.AccountManager;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import com.viewpagerindicator.IconPagerAdapter;
public class ContactsListActivity extends ActionBarActivity {
DemoCollectionPagerAdapter mDemoCollectionPagerAdapter;
ViewPager mViewPager;
private ContactDetailFragment mContactDetailFragment;
private boolean isTwoPaneLayout;
AccountManager mAccountManager;
Boolean checkAccount;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDemoCollectionPagerAdapter = new DemoCollectionPagerAdapter(getSupportFragmentManager());
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(R.color.purple));
getSupportActionBar().setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mDemoCollectionPagerAdapter);
isTwoPaneLayout = getResources().getBoolean(R.bool.has_two_panes);
PagerTabStrip pagerTabStrip = (PagerTabStrip) findViewById(R.id.pager_title_strip);
pagerTabStrip.setTextSpacing(0);
pagerTabStrip.setPadding(0, 0, 0, 10);
pagerTabStrip.setTextSize(1, 20);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.remove("android:support:fragments");
}
#Override
public void onBackPressed() {
startActivity(new Intent(ContactsListActivity.this, MenuScreen.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK));
this.finish();
overridePendingTransition(R.anim.card_rotate_in, R.anim.card_rotate_out);
}
#Override
protected void onDestroy() {
if(CommonUtility.dialog!=null){
CommonUtility.dialog.dismiss();
}
super.onDestroy();
}
#Override
public boolean onSearchRequested() {
boolean isSearchResultView = false;
return !isSearchResultView && super.onSearchRequested();
}
public static class DemoCollectionPagerAdapter extends FragmentPagerAdapter implements IconPagerAdapter {
protected static final String[] CONTENT = new String[]{"All Contacts", "Access Contacts"};
protected final int[] ICONS = new int[]{
R.drawable.all_contact,
R.drawable.access_contacts
};
private int mCount = CONTENT.length;
public DemoCollectionPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// All Contacts Fragment
return new ContactsListFragment();
case 1:
// Access Contacts Fragment
return new ContactsAccessFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return DemoCollectionPagerAdapter.CONTENT[position % CONTENT.length];
}
#Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
#Override
public int getCount() {
return mCount;
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
}
Error Log:
java.lang.NullPointerException
at com.hello.ContactsListFragment.onPrepareOptionsMenu(ContactsListFragment.java:236)
at android.support.v4.app.Fragment.performPrepareOptionsMenu(Fragment.java:1882)
at android.support.v4.app.FragmentManagerImpl.dispatchPrepareOptionsMenu(FragmentManager.java:2020)
at android.support.v4.app.FragmentActivity.onPreparePanel(FragmentActivity.java:459)
at android.support.v7.app.ActionBarActivity.superOnPreparePanel(ActionBarActivity.java:280)
at android.support.v7.app.ActionBarActivityDelegate$1.onPreparePanel(ActionBarActivityDelegate.java:84)
at android.support.v7.app.ActionBarActivityDelegateBase.preparePanel(ActionBarActivityDelegateBase.java:1006)
at android.support.v7.app.ActionBarActivityDelegateBase.doInvalidatePanelMenu(ActionBarActivityDelegateBase.java:1182)
at android.support.v7.app.ActionBarActivityDelegateBase.access$100(ActionBarActivityDelegateBase.java:79)
at android.support.v7.app.ActionBarActivityDelegateBase$1.run(ActionBarActivityDelegateBase.java:115)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5520)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)

can't override onContextItemSelected in Fragment

I'm trying to convert Activity to a fragment and can't override this methods : onCreateOptionsMenu,onOptionsItemSelected,onContextItemSelected.
,maybe some import statements are missing ? don't know what to do.Her is my Class file :
package com.wts.ui;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public class MainFragment extends Fragment {
protected final static int REQUEST_CODE = 1;
public static WordsDBAdapter dbAdapter;
private CustomAdapter cDataAdapter;
private Button button;
private EditText editWord;
private EditText editTranslate;
private ListView listView;
private String selectedWord;
private Cursor cursor;
// context menu
private final static int IDM_EDIT = 101;
private final static int IDM_DELETE = 102;
private final static int IDM_INFO = 103;
// options menu
private static final int IDM_ABOUT = 201;
private static final int IDM_EXIT = 202;
private static final int IDM_SETTINGS = 203;
private static final int IDM_QUESTION = 204;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dbAdapter = new WordsDBAdapter(getActivity());
dbAdapter.open();
displayListView();
registerForContextMenu(listView);
// ================ListView onLongClick========================
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
cursor = (Cursor) listView.getItemAtPosition(arg2);
selectedWord = cursor.getString(WordsDBAdapter.ID_COL);
return false;
}
});
// ================Button onClick========================
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String word = editWord.getText().toString();
String translate = editTranslate.getText().toString();
if (word.length() > 0 && translate.length() >= 0) {
Cursor cursor = dbAdapter.fetchWordsByName(word);// chek is
// word
// repeat
if (cursor.moveToFirst()) {
Toast.makeText(getActivity().getApplicationContext(),
getResources().getString(R.string.word_exist),
Toast.LENGTH_SHORT).show();
} else if (!CheckWordInput(word)
|| !CheckTranslateInput(translate)) {
Toast.makeText(
getActivity().getApplicationContext(),
getResources().getString(
R.string.incorrect_input),
Toast.LENGTH_SHORT).show();
} else {
dbAdapter.insertWord(word, translate, " ",
String.valueOf(false), 0, 0, new Date());
displayListView();
editWord.setText("");
editTranslate.setText("");
}
}
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_main, container, false);
button = (Button) view.findViewById(R.id.buttonAddWord);
listView = (ListView) view.findViewById(R.id.listWords);
editWord = (EditText) view.findViewById(R.id.editWord);
editTranslate = (EditText) view.findViewById(R.id.editTranslate);
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// setContentView(R.layout.activity_main);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId() == R.id.listWords) {
String[] menuItems = getResources().getStringArray(
R.array.contextMenuItems);
menu.add(Menu.NONE, IDM_EDIT, Menu.NONE,
menuItems[StartActivity.CONTEXT_MENU_EDIT]);
menu.add(Menu.NONE, IDM_INFO, Menu.NONE,
menuItems[StartActivity.CONTEXT_MENU_INFO]);
menu.add(Menu.NONE, IDM_DELETE, Menu.NONE,
menuItems[StartActivity.CONTEXT_MENU_DELETE]);
}
}
//
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case IDM_EDIT: {
Intent intent = new Intent(getActivity(), EditActivity.class);
intent.putExtra(getResources().getString(R.string.fstRow),
cursor.getString(WordsDBAdapter.WORD_COL));
intent.putExtra(getResources().getString(R.string.scndRow),
cursor.getString(WordsDBAdapter.TRANS_COL));
intent.putExtra(getResources().getString(R.string.thrdRow),
cursor.getString(WordsDBAdapter.DESC_COL));
startActivityForResult(intent, REQUEST_CODE);
}
break;
case IDM_DELETE:
dbAdapter.deleteWord(selectedWord);
displayListView();
break;
case IDM_INFO: {
Intent intent = new Intent(getActivity(), InformationActivity.class);
for (int i = 1; i <= InformationActivity.nListItems; i++)
intent.putExtra(String.valueOf(i), cursor.getString(i));
startActivity(intent);
}
break;
default:
return super.onContextItemSelected(item);
}
return true;
}
private void displayListView() {
// Cursor cursor = dbAdapter.fetchAllTranslated();
Cursor cursor = dbAdapter.fetchAllTranslated();
String[] columns = new String[] { WordsDBAdapter.KEY_WORD,
WordsDBAdapter.KEY_TRANSLATION, WordsDBAdapter.KEY_SUCCEEDED, };
int[] to = new int[] { R.id.textViewTranslate, R.id.textViewWord,
R.id.textViewSuccessPoints };
cDataAdapter = new CustomAdapter(getActivity(), R.layout.word_info,
cursor, columns, to);
listView.setAdapter(cDataAdapter);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.activity_main, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case IDM_ABOUT: {
Intent intent = new Intent(getActivity(), AboutActivity.class);
startActivity(intent);
break;
}
case IDM_EXIT: {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
getActivity().finish();
break;
}
case IDM_SETTINGS: {
Intent intent = new Intent(getActivity(), SettingsActivity.class);
startActivity(intent);
break;
}
case IDM_QUESTION: {
if (!StartActivity.isMainActivitySart)
getActivity().onBackPressed();
else {
Intent intent = new Intent(getActivity(),
QuestionActivity.class);
startActivity(intent);
}
}
break;
}
return true;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == Activity.RESULT_OK && requestCode == REQUEST_CODE) {
if (intent.hasExtra(getResources().getString(R.string.fstRow))) {
dbAdapter.changeValue(
selectedWord,
intent.getExtras().getString(
getResources().getString(R.string.fstRow)),
intent.getExtras().getString(
getResources().getString(R.string.scndRow)),
intent.getExtras().getString(
getResources().getString(R.string.thrdRow)),
null, null, null, null);
displayListView();
}
}
}
#Override
public void onResume() {
super.onResume();
SettingsManager.setPreferedLanguage(getActivity());// set language
displayListView();
}
public static boolean CheckTranslateInput(String str) {
Pattern inputPattern = Pattern.compile("[\\p{L} -]{0,25}");
Matcher inputMatcher = inputPattern.matcher(str);
return inputMatcher.matches();
}
public static boolean CheckWordInput(String str) {
Pattern inputPattern = Pattern.compile("[\\p{L} -]{1,25}");
Matcher inputMatcher = inputPattern.matcher(str);
return inputMatcher.matches();
}
#Override
public void onDetach() {
super.onDetach();
dbAdapter.close();
}
}
You have to think about what you want your Fragment to be - Fragment or SherlockFragment?
You import this:
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
And so, your overrides aren't overrides because Menu & friends are different classes right now than what Fragment needs - they are ActionBarSherlock's classes.
If you extend SherlockFragment instead, your overrides should work, and it is recommended to extend SherlockFragment if you are using ActionBarSherlock (which based on your tags, you are).
If you want to keep this as a regular fragment, then import:
android.view.Menu
android.view.MenuItem
android.view.MenuInflater

Categories

Resources