ListView.setAdapter(ArrayAdapter) is crashing app - java

I am trying to populate a listView with paired bluetooth devices. I tried doing so with a ListView in my MainActivity and it worked perfectly. However, when I tried it with a ListView in a different activity it crashed the app. I basically want to populate a ListView in a pop-up dialog box.
Here is the code:
activity_device_list.xml (MainActivity)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="1">
<ListView
android:id="#+id/listDevicesMain"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
device_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.12"
android:gravity="center"
android:paddingBottom="10dp"
android:paddingTop="10dp"
android:text="Paired Devices"
android:textSize="25sp" />
<ListView
android:id="#+id/listDevicesDialog"
android:layout_width="match_parent"
android:layout_height="395dp"
android:layout_weight="0.38" />
</LinearLayout>
DeviceList.java
package example.btmodule;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Set;
import static example.btmodule.R.layout.activity_device_list;
public class DeviceList extends AppCompatActivity {
ListView devicelist;
private BluetoothAdapter myBluetooth = null;
private Set<BluetoothDevice> pairedDevices;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_device_list);
myBluetooth = BluetoothAdapter.getDefaultAdapter();
if(myBluetooth == null)
{
//Show a mensag. that thedevice has no bluetooth adapter
Toast.makeText(getApplicationContext(), R.string.bluetooth_unavailable, Toast.LENGTH_LONG).show();
//finish apk
finish();
}
else {
if (myBluetooth.isEnabled()) {
} else {
//Ask to the user turn the bluetooth on
Intent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnBTon, 1);
}
}
}
private void pairedDevicesList()
{
pairedDevices = myBluetooth.getBondedDevices();
ArrayList list = new ArrayList();
devicelist = (ListView)findViewById(R.id.listDevicesDialog);
if (pairedDevices.size()>0)
{
for(BluetoothDevice bt : pairedDevices)
{
list.add(bt.getName() + "\n" + bt.getAddress()); //Get the device's name and the address
}
}
else
{
Toast.makeText(getApplicationContext(), R.string.no_devices_found, Toast.LENGTH_LONG).show();
}
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
devicelist.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
// menu item selection
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_connect:
showDialog();
pairedDevicesList();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// show the dialog for connected devices
private void showDialog(){
AlertDialog.Builder mBuilder = new AlertDialog.Builder(DeviceList.this);
View mView = getLayoutInflater().inflate(R.layout.device_dialog, null);
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
}
}
If I change devicelist to R.id.listDevicesMain the code works perfectly fine.

you calling the wrong list view the id of the list view as you have given is
<ListView
android:id="#+id/listDevicesMain"
android:layout_width="match_parent"
android:layout_height="match_parent" />
and you are trying to call the listview with id
devicelist = (ListView)findViewById(R.id.listDevicesDialog);
hope this will solve the issue.

devicelist = (ListView)findViewById(R.id.listDevicesDialog); - here you are looking for listDevicesDialog in activity layout, so devicesList becomes null. You should add devicelist = (ListView) mView.findViewById(R.id.listDevicesDialog); to showDialog() method and bring there rest of the operations related with searching for paired devices and setting adapter.
You can also call pairedDevicesList from showDialog and pass view where listDevicesDialog is:
private void pairedDevicesList(View dialogView)
{
pairedDevices = myBluetooth.getBondedDevices();
ArrayList list = new ArrayList();
devicelist = (ListView) dialogView.findViewById(R.id.listDevicesDialog);
...
}
// show the dialog for connected devices
private void showDialog()
{
AlertDialog.Builder mBuilder = new AlertDialog.Builder(DeviceList.this);
View mView = getLayoutInflater().inflate(R.layout.device_dialog, null);
mBuilder.setView(mView);
AlertDialog dialog = mBuilder.create();
dialog.show();
pairedDevicesList(mView);
}

Related

IllegalStateException: Could not find method in a parent or ancestor Context for android:onClick attribute defined on view class

When i click on a button with ID "btnDiscoverable_on_off" and "lvNewDevices" i get this error :
java.lang.IllegalStateException: Could not find method btnDiscover(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'btnFindUnpairedDevices'
This is the code :
import android.Manifest;
import android.app.Fragment;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class PrimoFragment extends Fragment implements
AdapterView.OnItemClickListener {
View myView;
private static final String TAG = "MainActivity";
BluetoothAdapter mBluetoothAdapter;
Button btnEnableDisable_Discoverable;
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
public DeviceListAdapter mDeviceListAdapter;
ListView lvNewDevices;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.primo_layout, container, false);
Button btnONOFF = (Button) myView.findViewById(R.id.btnONOFF);
btnEnableDisable_Discoverable = (Button) myView.findViewById(R.id.btnDiscoverable_on_off);
lvNewDevices = (ListView) myView.findViewById(R.id.lvNewDevices);
mBTDevices = new ArrayList<>();
//Broadcasts when bond state changes (ie:pairing)
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
getActivity().registerReceiver(mBroadcastReceiver4, filter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
lvNewDevices.setOnItemClickListener(PrimoFragment.this);
btnONOFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: enabling/disabling bluetooth.");
enableDisableBT();
}
});
return myView;
}
public void enableDisableBT(){
if(mBluetoothAdapter == null){
Log.d(TAG, "enableDisableBT: Does not have BT capabilities.");
}
if(!mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: enabling BT.");
Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBTIntent);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
getActivity().registerReceiver(mBroadcastReceiver1, BTIntent);
}
if(mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: disabling BT.");
mBluetoothAdapter.disable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
getActivity().registerReceiver(mBroadcastReceiver1, BTIntent);
}
}
public void btnEnableDisable_Discoverable(View view) {
Log.d(TAG, "btnEnableDisable_Discoverable: Making device discoverable for 300 seconds.");
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
IntentFilter intentFilter = new IntentFilter(mBluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
getActivity().registerReceiver(mBroadcastReceiver2,intentFilter);
}
public void btnDiscover(View view) {
Log.d(TAG, "btnDiscover: Looking for unpaired devices.");
if(mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "btnDiscover: Canceling discovery.");
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
getActivity().registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
if(!mBluetoothAdapter.isDiscovering()){
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
getActivity().registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
}
/**
* This method is required for all devices running API23+
* Android must programmatically check the permissions for bluetooth. Putting the proper permissions
* in the manifest is not enough.
*
* NOTE: This will only execute on versions > LOLLIPOP because it is not needed otherwise.
*/
private void checkBTPermissions() {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
int permissionCheck = this.getActivity().checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += this.getActivity().checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0) {
this.getActivity().requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
}
}else{
Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
}
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//first cancel discovery because its very memory intensive.
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "onItemClick: You Clicked on a device.");
String deviceName = mBTDevices.get(i).getName();
String deviceAddress = mBTDevices.get(i).getAddress();
Log.d(TAG, "onItemClick: deviceName = " + deviceName);
Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);
//create the bond.
//NOTE: Requires API 17+? I think this is JellyBean
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){
Log.d(TAG, "Trying to pair with " + deviceName);
mBTDevices.get(i).createBond();
}
}
}
XML code primo_fragment:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent" android:layout_height="match_parent">
<Button
android:text="ON/OFF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnONOFF"
android:layout_alignParentEnd="true" />
<Button
android:text="Enable Discoverable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnDiscoverable_on_off"
android:onClick="btnEnableDisable_Discoverable"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnFindUnpairedDevices"
android:text="Discover"
android:onClick="btnDiscover" />
<ListView
android:layout_width="wrap_content"
android:layout_height="150dp"
android:id="#+id/lvNewDevices"
android:layout_marginTop="62dp"
android:layout_alignParentStart="true" />
</RelativeLayout>
device_adapter_view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvDeviceName"
android:textSize="15sp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvDeviceAddress"
android:textSize="15sp"/>
</LinearLayout>
What is wrong with these two button ? I can't find the problem
Please follow this structure to use xml onClick attribute for Fragment. Hope your problem will be resolved.

must call setup() that takes a context and fragmentmanager - Rendering issue

I am trying to change my layout style using 'Design' option on android studio.
I get an error, saying that:
Exception raised during rendering: Must call setup() that takes a Context and FragmentManager (Details)
I can't understand what can cause this issue to occur, because when I run my app I can see the layout properly but can't edit it.
My class and layout are:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
android:baselineAligned="false"
android:orientation="vertical"
tools:layout_editor_absoluteY="81dp"
tools:layout_editor_absoluteX="0dp">
<TextView
android:id="#+id/item_page_product_name"
android:layout_width="368dp"
android:layout_height="wrap_content"
android:text="#string/nike_show"
android:textSize="18sp"
android:background="#null"
tools:layout_editor_absoluteX="8dp"
android:padding="3dp"
android:paddingStart="8dp"
tools:ignore="MissingConstraints,RtlSymmetry"
tools:layout_editor_absoluteY="8dp" />
<TextView
android:text="#string/item_page_item_des"
android:layout_width="326dp"
android:layout_height="wrap_content"
android:id="#+id/item_page_product_des"
tools:ignore="MissingConstraints"
android:layout_marginTop="8dp"
app:layout_constraintTop_toBottomOf="#+id/item_page_product_name"
android:layout_marginStart="1dp"
app:layout_constraintLeft_toRightOf="#+id/item_page_item_id" />
<TextView
android:text="#string/item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:layout_editor_absoluteX="8dp"
android:id="#+id/item_page_item_id"
tools:ignore="MissingConstraints"
android:layout_marginTop="8dp"
android:paddingStart="8dp"
app:layout_constraintTop_toBottomOf="#+id/item_page_product_name"
android:paddingRight="3dp"
android:paddingLeft="3dp" />
<android.support.v4.view.ViewPager
android:id="#+id/item_page_pager"
android:layout_width="368dp"
android:layout_height="213dp"
tools:layout_editor_absoluteX="8dp"
android:layout_marginTop="4dp"
app:layout_constraintTop_toBottomOf="#+id/item_page_product_des"
tools:ignore="MissingConstraints" />
<android.support.v4.app.FragmentTabHost
android:id="#+id/tabsHostItem"
android:layout_width="368dp"
android:layout_height="325dp"
tools:layout_editor_absoluteX="8dp"
tools:ignore="MissingConstraints"
app:layout_constraintTop_toBottomOf="#+id/item_page_pager">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/tab"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:orientation="vertical"
tools:ignore="UselessParent">
<!--<TextView-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent"-->
<!--android:text="#string/this_is_tab_1" />-->
</FrameLayout>
<!--<LinearLayout-->
<!--android:id="#+id/tab2"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent"-->
<!--android:orientation="vertical">-->
<!--<TextView-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent"-->
<!--android:text="#string/this_is_tab_2" />-->
<!--</LinearLayout>-->
<!--<LinearLayout-->
<!--android:id="#+id/tab3"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent"-->
<!--android:orientation="vertical">-->
<!--<TextView-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="match_parent"-->
<!--android:text="#string/this_is_tab_3" />-->
<!--</LinearLayout>-->
</FrameLayout>
</LinearLayout>
</android.support.v4.app.FragmentTabHost>
</android.support.constraint.ConstraintLayout>
Class:
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.app.NavUtils;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.goldbergtom.cricket.adapters.ViewPagerAdapter;
import com.goldbergtom.cricket.fragments.DescriptionFragment;
import controller.ControllerDao;
public class ItemPageActivity extends AppCompatActivity {
private android.support.v4.app.FragmentTabHost mTabHost;
ViewPager viewPager;
PagerAdapter adapter;
int[] flag;
private LinearLayout mGallery;
private int[] mImgIds;
private LayoutInflater mInflater;
private HorizontalScrollView horizontalScrollView;
private ImageButton back;
private ImageButton www;
private ImageButton settings;
private TextView productMainTitle;
private TextView productId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_page);
mInflater = LayoutInflater.from(this);
productMainTitle = (TextView)findViewById(R.id.item_page_product_name);
productId = (TextView)findViewById(R.id.item_page_product_des);
// productMainTitle = (TextView)findViewById(R.id.item_page_product_name);
// productMainTitle = (TextView)findViewById(R.id.item_page_product_name);
String pMT = ControllerDao.currentSessionUser.getProducts()[0].get_title();
String pid = ControllerDao.currentSessionUser.getProducts()[0].getId();
productMainTitle.setText(pMT);
productId.setText(pid);
// TODO : yahav - remove the comments on the following code and look what it does
// android.support.v7.app.ActionBar actionBar = getSupportActionBar();
// actionBar.setDisplayShowTitleEnabled(false);
// actionBar.setDisplayShowHomeEnabled(false);
//
// View mCustomView = mInflater.inflate(R.layout.cricket_action_bar, null);
//
// actionBar.setCustomView(mCustomView);
// actionBar.setDisplayShowCustomEnabled(true);
//
// back = (ImageButton)findViewById(R.id.toolbar_back);
// back.setOnClickListener(backButtonFromItemActivity);
//
// www = (ImageButton)findViewById(R.id.toolbar_www);
// www.setOnClickListener(wwwButtonFromItemActivity);
//
// settings = (ImageButton)findViewById(R.id.toolbar_settings1);
// settings.setOnClickListener(settingsButtonFromItemActivity);
//
flag = new int[] { R.drawable.ic_1 , R.drawable.ic_2 , R.drawable.ic_3 };
// Locate the ViewPager in viewpager_main.xml
viewPager = (ViewPager) findViewById(R.id.item_page_pager);
// Pass results to ViewPagerAdapter Class
adapter = new ViewPagerAdapter(ItemPageActivity.this, flag);
// Binds the Adapter to the ViewPager
viewPager.setAdapter(adapter);
mTabHost = (FragmentTabHost)findViewById(R.id.tabsHostItem);
// FragmentManager fm = getFragmentManager();
// android.app.FragmentTransaction ft = fm.beginTransaction();
// ft.commit();
mTabHost.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
mTabHost.addTab(
mTabHost.newTabSpec("tab1").setIndicator("DESCRIPTION",null),DescriptionFragment.class,null);
mTabHost.addTab(
mTabHost.newTabSpec("tab2").setIndicator("HISTORY",null),DescriptionFragment.class,null);
mTabHost.addTab(
mTabHost.newTabSpec("tab3").setIndicator("ALERTS",null),DescriptionFragment.class,null);
//Tab 1
// TabHost.TabSpec spec = host.newTabSpec("DESCRIPTION");
// spec.setContent(R.id.tab1);
// spec.setIndicator("Tab One");
// host.addTab(spec);
//
// //Tab 2
// spec = host.newTabSpec("HISTORY");
// //spec.setContent(R.layout.fragment_description);
// spec.setContent(R.id.tab2);
// spec.setIndicator("Tab Two");
// host.addTab(spec);
//
// //Tab 3
// spec = host.newTabSpec("ALERTS");
// spec.setContent(R.id.tab3);
// spec.setIndicator("Tab Three");
// host.addTab(spec);
// CricketDao.GetDataTask gdt = new CricketDao.GetDataTask();
// String s = null;
// JSONObject jObject = null, subject = null;
// JSONArray arr = null;
// String title=null;
// try {
// // TODO : Place resonse as USER object to const
// s = gdt.execute("https://cricketweb.herokuapp.com/checkLogin").get();
// } catch (InterruptedException e) {
// e.printStackTrace();
// } catch (ExecutionException e) {
// e.printStackTrace();
// }
}
public boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater().inflate(R.menu.menu_item_activity, menu);
return true;
}
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.
switch (item.getItemId()){
// when clicking on the URL icon, it will open the product page through browser.
case R.id.action_web:
startActivity(new Intent(this, LoginActivity.class));
return true;
// when clicking on delete item it will delete the item from wish list and go back to wish list page.
case R.id.delete_item:
startActivity(new Intent(this, WishListActivity.class));
return true;
// when clicking on purchased item, it will stay on this activity and change on DB from 0 to 1 (help us with adaptation)
case R.id.purchased_item:
startActivity(new Intent(this, LoginActivity.class));
return true;
// when clicking on settings, it will give the user another view of settings option.
case R.id.action_settings:
startActivity(new Intent(this, LoginActivity.class));
return true;
// when clicking on back icon it will go back to previous screen.
case R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
View.OnClickListener backButtonFromItemActivity = new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "backButtonFromItemActivity", Toast.LENGTH_SHORT).show();
}
};
View.OnClickListener wwwButtonFromItemActivity = new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "wwwButtonFromItemActivity", Toast.LENGTH_SHORT).show();
}
};
View.OnClickListener settingsButtonFromItemActivity = new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "settingsButtonFromItemActivity", Toast.LENGTH_SHORT).show();
}
};
private void initData()
{
mImgIds = new int[] { R.drawable.ic_1, R.drawable.ic_2, R.drawable.ic_3,R.drawable.ic_4
};
}
public void toggle_contents(View v){
new DescriptionFragment().toggle_contents(v);
}
public void toggle_contents2(View view) {
new DescriptionFragment().toggle_contents2(view);
}
}
This rendering error occurs because the android studio layout renderer still uses the deprecated setup() method. there's actually an open issue about this here
If setup properly like you have it will work as intended when you run the app. the only downside is that you will not get to see the rendered view on the editor until the android team posts a fix for this.

Android dynamic listview

I want to make a ListView that gets its elements(strings) from user input. I have a button that directs the user to another activity and while in it, the user enters a name and presses another button to come back to the original activity. The same button gets and adds a string to the ArrayAdapter that the ListView uses and displays it as an element in the ListView. It doesn't seem to work and I know it's a stupid mistake, but I'm fresh to android development and this in particular I haven't done before.
Here's all the code:
the MainActivity
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> simpleArray =new ArrayList<String>();
ListAdapter simpleAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
simpleArray);
ListView lv = (ListView) findViewById(R.id.lv);
lv.setAdapter(simpleAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void enterActivity(View view) {
Intent toEnterSecond = new Intent(this, SecondActivity.class);
startActivity(toEnterSecond);
}
}
The second acitivity
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import java.util.ArrayList;
public class SecondActivity extends Activity{
private EditText projectName;
ArrayList simpleArray;
ArrayAdapter simpleAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
projectName = (EditText) findViewById(R.id.eTxt);
}
public void getBack(View view) {
String projectCalling = String.valueOf(projectName.getText());
simpleArray.add(projectCalling);
simpleAdapter.notifyDataSetChanged();
Intent comeBack = new Intent(this, MainActivity.class);
startActivity(comeBack);
}
}
And the layouts
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="80dp"
android:id="#+id/simpleButton"
android:text="click me plox"
android:onClick="enterActivity"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/simpleButton"
android:id="#+id/lv">
</ListView>
</RelativeLayout>
//
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="20dp"
android:text="Enter the name of your project:"
android:id="#+id/txt"/>
<EditText
android:layout_width="200dp"
android:layout_height="40dp"
android:layout_below="#+id/txt"
android:id="#+id/eTxt"/>
<Button
android:layout_width="100dp"
android:layout_height="60dp"
android:layout_below="#+id/eTxt"
android:text="click"
android:onClick="getBack"/>
</RelativeLayout>
Explanation:
You can start SecondActivity with startActivityForResult() instead of startActivity as answered here and in onResultActivity method you can call simpleAdapter.notifyDataSetChanged();. Don't call simpleAdapter.notifyDataSetChanged(); in SecondActivity.
To learn how to use startActivityForResult check this.
Also use finish() instead of
Intent comeBack = new Intent(this, MainActivity.class);
startActivity(comeBack);
in SecondActivity to go back to MainActivity.
Solution:
Change MainActivity enterActivity method to this:
...
public void enterActivity(View view) {
Intent toEnterSecond = new Intent(this, SecondActivity.class);
startActivityForResult(toEnterSecond,1);
}
Add this to end of SecondActivity getBack method:
MainActivity.simpleArray.add(projectCalling);
Intent returnIntent = new Intent();
setResult(RESULT_OK,returnIntent);
finish();
Finally add this new method to MainActivity:
protected void onActivityResult(int requestCode, int resultCode, Intent data{
if (requestCode == 1) {
if(resultCode == RESULT_OK){
((ArrayAdapter) simpleAdapter).notifyDataSetChanged();
}
}
}
To be able to access simpleAdapter, you need to define it outside of onCreate:
public class MainActivity extends ActionBarActivity {
private ListAdapter simpleAdapter;
public static ArrayList<String> simpleArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
simpleArray =new ArrayList<String>();
simpleAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
simpleArray);
...
}

Why is my Bluetooth application Crashing

I am working on a bluetooth application but my application crash .Here is my MainActivity.java
package com.race_gurram.bluetoothadapter;
import java.util.ArrayList;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button on, off, get, bring;
private BluetoothAdapter BA;
private Set<BluetoothDevice> pairedDevices;
private ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
on = (Button) findViewById(R.id.on);
off = (Button) findViewById(R.id.off);
get = (Button) findViewById(R.id.get);
bring = (Button) findViewById(R.id.list);
lv = (ListView) findViewById(R.id.listView1);
BA = BluetoothAdapter.getDefaultAdapter();
}
public void on(View view)
{
if(!BA.isEnabled())
{
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn,0);
Toast.makeText(getApplicationContext(), "Turned On", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "Already on", Toast.LENGTH_SHORT).show();
}
}
public void list(View view)
{
pairedDevices = BA.getBondedDevices();
ArrayList list = new ArrayList();
for(BluetoothDevice bt : pairedDevices)
list.add(BA.getName());
Toast.makeText(getApplicationContext(), "Searching for devices", Toast.LENGTH_SHORT).show();
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,list);
lv.setAdapter(adapter);
}
public void get()
{
Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(getVisible,0);
}
public void off()
{
BA.disable();
Toast.makeText(getApplicationContext(), "Turned off", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
and this is my activity.xml file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ScrollView
android:id="#+id/scrollView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/on"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="on"
android:text="#string/on" />
<Button
android:id="#+id/get"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="get"
android:text="#string/get" />
<Button
android:id="#+id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="list"
android:text="#string/bring" />
<Button
android:id="#+id/off"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="off"
android:text="#string/off" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:visibility="visible" >
</ListView>
</LinearLayout>
</ScrollView>
</RelativeLayout>
Whenever I onclick on a button the application crashes... Please help me out with this .. thank in advance.
On get and off method, there should be a View parameter, right?
public void get(View v) {
Intent getVisible = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(getVisible,0);
} public void off(View v) {
BA.disable();
Toast.makeText(getApplicationContext(), "Turned off", Toast.LENGTH_SHORT).show(); }
Perhaps it is when you click the list button. Assuming that the phone has 0 bonded devices,
paired.getBondedDevices() will probably return null and the program crashes due to a NullPointerException.
pairedDevices = BA.getBondedDevices();
ArrayList list = new ArrayList();
if(pairedDevices != null) {
for(BluetoothDevice bt : pairedDevices)
list.add(BA.getName());
}

How do you change the text color of the list view

OK so the trick that works with a textView doesn't work with this.
So I know this has got to be simple.... Right?
because i might help me out with adding pictures for this later.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/logo"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignParentBottom="true"
android:layout_below="#+id/textView1"
android:paddingLeft="8dp"
android:paddingRight="8dp" >
</ListView>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:text="#string/welcome"
android:textColor="#b70000"
android:textSize="16sp" />
</RelativeLayout>
I use this to call it and add to the listview inside the java code.
package com.example.boonehallfrightnightsapp;
import android.os.Bundle;
import android.view.Menu;
import android.app.ListActivity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity
{
static final String[] CHOICES = new String[]
{
"Haunted House",
"Amy's Nightmare",
"Zombie Town",
"Haunted Hayride",
"Quit"
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fn_main);
//found this part on an example
//Set up ArrayAdaptor for the options
setListAdapter(new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, CHOICES));
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setTextFilterEnabled(true);
//part of example
//Set up the listener for user clicks on the list
setListClickListener();
//this toast is for when it opens
Toast.makeText(this, "I see your fear...", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void setListClickListener()
{
//Set up the click listener for the options
getListView().setOnItemClickListener
(
new OnItemClickListener()
{
//#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
switch(arg2)
{
case 0: launchHousePage();
break;
case 1: launchNightmarePage();
break;
case 2: launchZombiePage();
break;
case 3: launchHayridePage();
break;
case 4: finish();
break;
default: break;
}
}
}//END OnItemClickListener
);//END setOnItemClickListener
}//END setListClickListener
//goes to haunted house
protected void launchHousePage()
{
//Set up Intent
Intent launchHouse = new Intent(this, HauntedHouseList.class);
startActivity(launchHouse);
}//END launchHousePage
//goes to Amy's Nightmare
protected void launchNightmarePage()
{
//Set up Intent
Intent launchnightmare = new Intent(this, NightmareList.class);
startActivity(launchnightmare);
}//END launchNightmarePage
//goes to Amy's Nightmare
protected void launchZombiePage()
{
//Set up Intent
Intent launchzombies = new Intent(this, ZombieTownList.class);
startActivity(launchzombies);
}//END launchZombiePage
//goes to haunted house
protected void launchHayridePage()
{
//Set up Intent
Intent launchhayride = new Intent(this, HauntedHayrideList.class);
startActivity(launchhayride);
}//END launchHayridePage
}
You've specified a built-in Adapter (ArrayAdapter) using item layout android.R.layout.simple_list_item_1.
if you want custom layout, you can copy the simple_list_item_1.xml layout from Android SDK (look in the platforms/android-18/data/res/layout folder) into your project and modify it. For example you call it my_simple_list_item_1.xml.
Then modify your code to use your layout, and not android.R.layout.simple_list_item_1:
setListAdapter(new ArrayAdapter<String>(this, R.layout.my_simple_list_item_1, CHOICES));
You'll see that Androids simple_list_item_1 layout is just a TextView, and you can add the textColor attribute to it and modify to your liking.

Categories

Resources