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.
Related
In my Android Studio project I have a fragment that I created to display the profile page of a dating app. I also have a signUpActivity that is used in place of the mainActivity that leads to another activity called secondActivity. My fragment is called profileFragment. What I am trying to do is put the profileFragment into the first tab of my secondActivity. Right now when I run the project and create a valid dating profile I get the fragment in the background with the second activity with its tabs in the foreground. What is the easiest way to add my fragment to a tab with what I have right now? I attatched the code for the xml code and java code for the secondActivity and the profileFragment. I will also attatch a link to my github if it helps to answer my question:
https://github.com/alasali1/Form
Below is the code for my secondActivity:
package com.example.form;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.tabs.TabLayout;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import com.example.form.ui.main.SectionsPagerAdapter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class SecondActivity extends AppCompatActivity {
private static final String TAG = SecondActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(this, getSupportFragmentManager());
ViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(sectionsPagerAdapter);
TabLayout tabs = findViewById(R.id.tabs);
tabs.setupWithViewPager(viewPager);
FloatingActionButton fab = findViewById(R.id.fab);
//fragment
ProfileFragment profileFragment = new ProfileFragment();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.fragment_profile, profileFragment, "profileFragment");
transaction.commit();
Log.i(TAG, "onCreate()");
//Get the bundle
Bundle bundle = getIntent().getExtras();
String stringDate = bundle.getString("date");
String stringName = bundle.getString("name");
String stringJob = bundle.getString("job");
String stringDescription = bundle.getString("description");
//set arguments
profileFragment.setArguments(bundle);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
//turn date string into date object
public static Calendar convertDate(String stringDate) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Calendar date = Calendar.getInstance();
date.setTime(sdf.parse(stringDate));
return date;
}
public static boolean checkAge(Calendar date){
Calendar today = Calendar.getInstance();
int checkYear = today.get(Calendar.YEAR) -18;
int yob = date.get(Calendar.YEAR);
int mob = date.get(Calendar.MONTH);
int dob = date.get(Calendar.DAY_OF_MONTH);
if(date.after(today)){
return false;
}
if(yob > checkYear){
return false;
} else if(mob > today.get(Calendar.MONTH)){
return false;
} else if(dob > today.get(Calendar.DAY_OF_MONTH)){
return false;
} else{
return true;
}
}
#Override
protected void onRestart() {
super.onRestart();
Log.i(TAG, "onRestart()");
}
#Override
protected void onStart() {
super.onStart();
Log.i(TAG, "onStart()");
}
#Override
protected void onResume() {
super.onResume();
Log.i(TAG, "onResume()");
}
#Override
protected void onPause() {
super.onPause();
Log.i(TAG, "onPause()");
}
#Override
protected void onStop() {
super.onStop();
Log.i(TAG, "onStop()");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy()");
}
}
While the java code for my fragment is :
package com.example.form;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.text.ParseException;
import java.util.Calendar;
public class ProfileFragment extends Fragment {
TextView textView, jobView, ageView, descriptionView;
ImageView imageView;
public ProfileFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profile, container, false);
String stringDate = getArguments().getString("date");
String stringName = getArguments().getString("name");
String stringJob = getArguments().getString("job");
String stringDescription = getArguments().getString("description");
//make imageView
imageView = v.findViewById(R.id.imageView);
//make textview
textView = v.findViewById(R.id.textView);
//make job textview
jobView = v.findViewById(R.id.job);
//add input to jobView
if(stringJob.equals("")){
jobView.append("N/A");
} else{
jobView.setText(stringJob);
}
//make descriptionView
descriptionView = v.findViewById(R.id.description);
//add input to descriptionView
descriptionView.append(" " +stringDescription);
//make ageView
ageView= v.findViewById(R.id.age);
//make age variable
int age = 0;
//Get age
try {
Calendar birth = ConfirmActivity.convertDate(stringDate);
Calendar today = Calendar.getInstance();
if(today.get(Calendar.DAY_OF_YEAR) < birth.get(Calendar.DAY_OF_YEAR)){
age= today.get(Calendar.YEAR) - birth.get(Calendar.YEAR) - 1;
}
else{
age= today.get(Calendar.YEAR) - birth.get(Calendar.YEAR);
}
} catch (ParseException e) {
e.printStackTrace();
}
//set age
ageView.append(String.valueOf(age));
//convert date
try {
Calendar date = ConfirmActivity.convertDate(stringDate);
//compare date
if(ConfirmActivity.checkAge(date)){
textView.setText(" "+ stringName +" Thank you for signing up");
}
else{
imageView.equals(null);
textView.append(" Please try again when you're older");
jobView.equals("");
ageView.equals("");
}
} catch (ParseException e) {
e.printStackTrace();
}
return v;
}
}
The XML for my second activity is :
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SecondActivity">
<FrameLayout
android:id="#+id/fragment_profile"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/Theme.Form.AppBarOverlay">
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:minHeight="?actionBarSize"
android:padding="#dimen/appbar_padding"
android:text="#string/app_name"
android:textAppearance="#style/TextAppearance.Widget.AppCompat.Toolbar.Title" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary">
</com.google.android.material.tabs.TabLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
While the xml for the fragment is :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ConfirmActivity"
android:orientation="vertical"
android:weightSum="4">
<ImageView
android:id="#+id/imageView"
android:layout_width="203dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
android:src="#drawable/blank_pic"
/>
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hi"
android:layout_gravity="center_horizontal"
/>
<TextView
android:id="#+id/job"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/job"
android:layout_gravity="center_horizontal"
/>
<TextView
android:id="#+id/age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/age"
android:layout_gravity="center_horizontal"
android:layout_weight="1"
/>
<TextView
android:id="#+id/description"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/description"
android:layout_weight="1"
/>
</LinearLayout>
Here is a screenshot indicating my problem. The fragment that Iwant to put into the tab is static in the background whereas the hello world string in the foreground is inside of the tabs so they change when I click on a new tab. I want to put my fragment inside of the first tab instead of it being in the background if that makes sense:
The problem is here:
ProfileFragment profileFragment = new ProfileFragment();
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.fragment_profile, profileFragment, "profileFragment");
transaction.commit();
This code creates an instance of ProfileFragment and adds it directly to the activity. Instead, you should create fragments that belong in a tab in the SectionsPagerAdapter and use it to manage which fragment is shown according to which tab is selected.
Hum, if i understood you want to use the view-pager to sweep the pages of each tab.
You don't need a "FrameLayout", because the Adapter of the ViewPager2 switch the fragment by giving the FragmentManager to the Adapter of the ViewPager2.
in the xml switch the ViewPager to ViewPager2.
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Create a new class that extends the FragmentStateAdapter, in this class you will be giving the number of the fragments that the ViewPager2 will be using to sweep between them.
public class FragmentAdapter_ViewPager extends FragmentStateAdapter {
public FragmentStateAdapter_ViewPager(#NonNull FragmentManager fragmentManager, #NonNull Lifecycle lifecycle) {
super(fragmentManager, lifecycle);
}
#NonNull
#Override
public Fragment createFragment(int position) {
switch (position) {
case 0://FIRST TAB
return new Fragment_Two();
case 1://SECOND TAB
return new Fragment_Three();
default:
return new Profile_Fragment();
}
return null;
}
#Override
public int getItemCount() {
return 3;
}
}
If you have more than one fragment to show in the tabs you can increment in the "createFragment()" method, just don't forget to say how many fragments will show in the method "getItemCount()".
Now in the SecoundActivity you can configure the new ViewPager2 with the Adapter and a new the LayoutMediator that synchronize them together.
//The Adapter of ViewPager2 that will switch the Fragments
viewPager2.setAdapter(new FragmentStateAdapter_ViewPager(getChildFragmentManager(), getLifecycle()));
//The LayoutMediator that will synchronize with the tabs
new TabLayoutMediator(tabLayout, viewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
#Override
public void onConfigureTab(#NonNull TabLayout.Tab tab, int position) {
tab.setText("TAB NAME"[position]);
}
}).attach();
Try to take a look int the GUIDE PAGE in:
Create swipe views with tabs using ViewPager2
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);
}
I am developing my first Android application as part of a college project. I am relatively new to java. My application consists of a bottom navigation, which contains 4 separate pages. Within these pages I have a head section, containing a title, contact button and logout button.
Underneath the head section I wish to have a midsection which will in itself contain 3 swipe panels containing information. Essentially there should be 3 panels for each page, with there being 4 pages (So 4 sets of 3 swipe panels).
This is where I'm having difficulty.. I'm unsure of how to nest the fragments so that only that midsection will be swipe-able. Here is a screenshot of what I have so far:
Screenshot of app
Here is my Code for my MainActivity.java class:
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
private static final String SELECTED_ITEM = "arg_selected_item";
private BottomNavigationView mBottomNav;
private int mSelectedItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBottomNav = (BottomNavigationView) findViewById(R.id.navigation);
mBottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
selectFragment(item);
return true;
}
});
MenuItem selectedItem;
if (savedInstanceState != null) {
mSelectedItem = savedInstanceState.getInt(SELECTED_ITEM, 0);
selectedItem = mBottomNav.getMenu().findItem(mSelectedItem);
} else {
selectedItem = mBottomNav.getMenu().getItem(0);
}
selectFragment(selectedItem);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(SELECTED_ITEM, mSelectedItem);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
MenuItem homeItem = mBottomNav.getMenu().getItem(0);
if (mSelectedItem != homeItem.getItemId()) {
// select home item
selectFragment(homeItem);
} else {
super.onBackPressed();
}
}
private void selectFragment(MenuItem item) {
Fragment frag = null;
// init corresponding fragment
switch (item.getItemId()) {
case R.id.menu_home:
frag = MenuFragment.newInstance(getString(R.string.text_home),
getString(R.string.test_home));
break;
case R.id.menu_notifications:
//Call to a function that does the stuff here
frag = MenuFragment.newInstance(getString(R.string.text_notifications),
getString(R.string.test_notifications));
break;
case R.id.menu_search:
frag = MenuFragment.newInstance(getString(R.string.text_search),
getString(R.string.test_search));
break;
case R.id.menu_followed:
frag = MenuFragment.newInstance(getString(R.string.text_follow),
getString(R.string.test_follow));
}
// update selected item
mSelectedItem = item.getItemId();
// uncheck the other items.
for (int i = 0; i< mBottomNav.getMenu().size(); i++) {
MenuItem menuItem = mBottomNav.getMenu().getItem(i);
menuItem.setChecked(menuItem.getItemId() == item.getItemId());
}
if (frag != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.container, frag, frag.getTag());
ft.commit();
}
}
}
Here is the acitivity_main.xml file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:design="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.socialivemusic.socialivetestproject.MainActivity">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#ff292929">
</FrameLayout>
<android.support.design.widget.BottomNavigationView
android:id="#+id/navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_weight="0.06"
android:background="#ff000000"
android:textAlignment="center"
design:menu="#menu/bottom_nav_items" />
</LinearLayout>
And here is my MenuFragment.java class:
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import org.w3c.dom.Text;
public class MenuFragment extends Fragment {
private static final String ARG_TEXT = "arg_text";
private static final String ARG_TESTSTRING = "arg_testString";
private String mText;
private String mTest;
private View mContent;
private TextView mTextView;
private TextView mTestView;
private Button contactButton;
private Button logoutButton;
public static Fragment newInstance(String text, String testString) {
Fragment frag = new MenuFragment();
Bundle args = new Bundle();
args.putString(ARG_TEXT, text);
args.putString(ARG_TESTSTRING, testString);
frag.setArguments(args);
return frag;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_menu, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// retrieve text and color from bundle or savedInstanceState
if (savedInstanceState == null) {
Bundle args = getArguments();
mText = args.getString(ARG_TEXT);
mTest = args.getString(ARG_TESTSTRING);
} else {
mText = savedInstanceState.getString(ARG_TEXT);
mTest = savedInstanceState.getString(ARG_TESTSTRING);
}
// initialize views
mContent = view.findViewById(R.id.fragment_content);
mTextView = (TextView) view.findViewById(R.id.text);
mTestView = (TextView) view.findViewById(R.id.test);
contactButton = (Button) view.findViewById(R.id.contactButton);
logoutButton = (Button) view.findViewById(R.id.logoutbutton);
// set text and background color
mTextView.setText(mText);
mTestView.setText(mTest);
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(ARG_TEXT, mText);
outState.putString(ARG_TESTSTRING, mTest);
super.onSaveInstanceState(outState);
}
}
Here is the fragments_menu.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.socialivemusic.socialivetestproject.MenuFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_marginLeft="17dp"
android:layout_marginRight="17dp"
android:layout_height="150dp"
android:layout_marginTop="15dp"
android:background="#ff434343"
android:weightSum="1">
<Button
android:text="CONTACT"
android:textColor="#ffffff"
android:layout_width="420dp"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_height="90dp"
android:layout_gravity="center"
android:id="#+id/contactButton"
android:layout_weight="0.33"
android:background="#drawable/round_button"
android:textSize="20sp"/>
<TextView
android:id="#+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:layout_gravity="center"
android:textColor="#969696"
android:textSize="40sp"
android:textStyle="bold"
android:layout_weight="0.355"
/>
<Button
android:text="LOGOUT"
android:textColor="#ffffff"
android:layout_width="420dp"
android:layout_height="90dp"
android:layout_gravity="center"
android:id="#+id/logoutbutton"
android:layout_weight="0.33"
android:background="#drawable/logout_button"
android:textSize="20sp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_marginLeft="17dp"
android:layout_marginRight="17dp"
android:layout_height="match_parent"
android:layout_marginBottom="15dp"
android:layout_marginTop="185dp"
android:background="#ff434343">
<TextView
android:id="#+id/test"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
</RelativeLayout>
The second LinearLayout in the above file is the one which should be the swipe-panel. The only other files on the project are xml files dealing with layout of the bottom navigation bar itself, so not relevant to the trouble I'm having.
Does anyone have any recommendations on how to approach this? A helping hand on how to start this part of the project would be amazing! Thanks in advance!
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());
}
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.