How add custom dynamic layout in a dialog box? - android-layout

i am new to android java programming. I am adding a custom dynamic layout to a dialog box. i have 2 classes , Mainactivity.java and Getval.java
The Mainactivity.java create a dialoge and Getval generates dynamic layout at run time.
Every thing works good but when it tried to call Getval.java's method, it gives an exception. here is the code of both classes.
The g.setval(); in Mainactivity.java cause problem.
:::::Mainactivity.java:::::
public class MainActivity extends Activity {
private Button button;
public Getval g=new Getval();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button= (Button) findViewById(R.id.buttonShowCustomDialog);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//set up dialog
g.setval();
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.attributewin);
dialog.setTitle("Attribute Window");
dialog.setCancelable(true);
dialog.show();
}
});
::::Getval::::
public class Getval extends Activity{
String names[]={"test","chaeck","kajsdhasj","dlasdig"};
String values[]={"test","chaeck","kajsdhasj","dlasdig"};
String test[]={"Attribut","Value"};
public void setval(){
TableLayout tl = (TableLayout) findViewById(R.id.tly);
Button b=new Button(this);
for (int i = 0; i < names.length; i++) {
//Row
TableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
//TextViews
TextView tv0 = new TextView(this);
tv0.setText(names[i]);
tv0.setMaxWidth(75);
TextView tv1 = new TextView(this);
tv1.setText(values[i]);
tv1.setMaxWidth(150);
View line = new View(this);
line.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 1));
line.setBackgroundColor(Color.BLACK);
//Setting Views
tr.addView(tv0);
tr.addView(tv1);
tl.addView(tr);
tl.addView(line);
}
//Button Row
TableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
tr.setGravity(0x11);
b.setId(100);
b.setText("Return");
b.setGravity(0x11);
tr.addView(b);
tl.addView(tr);
}
}

Looking over this without seeing your xml or complete code (or exception that is thrown), I would be willing to guess that you are trying to inflate/modify a view (R.id.tly) from an activity other than the one where it was originally inflated from (MainActivity).
Generally speaking, you can't do this without doing some tricks with cross activity handlers or other methods. Perhaps change your code to inflate the views (R.id.tly) in MainActivity (and in your dialog if it is inside of R.layout.attributewin), do your processing in Getval, return them to MainActivity so it can populate the views.
But again, this is just a guess, since I don't see your xml or exception.

Related

use Onclick in extends PagerAdapter

Hi I’m trying to create a horizontal slide where each horizontal page will have a button that will call a Dialog but onClick is not working in extends Pageradapter can anyone tell me what I’m doing wrong?
I gave the name onClickApprove to onClick that I want you to call Dialog. This Dialog is calling an Activity with a Ratingbar to make an assessment.
Thank you.
public class SliderAdapterUsado extends PagerAdapter {
Context context;
LayoutInflater layoutInflater;
BottomSheetDialog dialog;
Button show;
public SliderAdapterUsado(Context context){
this.context = context;
}
public String[] slide_rota ={
"Titulo1",
"Titulo2"
};
public String[] slide_nome={
"Descrção do titulo 1",
"Descrção do titulo 2"
};
#Override
public int getCount(){
return slide_rota.length;
}
#Override
public boolean isViewFromObject(View view, Object object){
return view == (LinearLayout) object;
}
#Override
public Object instantiateItem(ViewGroup container, int position){
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.slide_layout_usados, container, false);
TextView slideHeading = view.findViewById(R.id.slide_rota);
TextView slideDescricao = view.findViewById(R.id.slide_nome);
slideHeading.setText(slide_rota[position]);
slideDescricao.setText(slide_nome[position]);
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object){
container.removeView((LinearLayout)object);
}
public void onClickAvaliar(View view) {
show = view.findViewById(R.id.show);
dialog = new BottomSheetDialog(dialog.getContext());
show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
createDialog();
dialog.show();
}
});
dialog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
}
private void createDialog(){
View view = layoutInflater.inflate(R.layout.activity_rating, null, false);
Button FeedBack = view.findViewById(R.id.FeedBack);
FeedBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.setContentView(view);
}
}
Please read the documentation.
Note this in particular (emphasis mine):
To define the click event handler for a button, add the android:onClick attribute to the element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.
The expectation is that the value set on the onClick xml attribute will be a method on the hosting Activity. Yours is in the adapter. That's why it doesn't work.
So either move that method to the hosting activity, or just handle the click event explicitly:
...
TextView slideHeading = view.findViewById(R.id.slide_rota);
TextView slideDescricao = view.findViewById(R.id.slide_nome);
Button slideButton = view.findViewById(R.id.slide_button);
slideButton.setOnClickListener (...)
...

"java.lang.IllegalArgumentException: view must not be null" Program Closes when navigated

The app closes whenever I navigate to ProfileActivity.
FATAL EXCEPTION: main Process: hfad.com.hallofmemesprototype, PID:
19092 java.lang.RuntimeException: Unable to start activity
ComponentInfo{hfad.com.hallofmemesprototype/hfad.com.hallofmemesprototype.Profile.ProfileActivity}:
java.lang.IllegalArgumentException: view must not be null
Here's the "ProfileActivity" code.
public class ProfileActivity extends AppCompatActivity {
private static final int ACTIVITY_NUM = 3;
private Context mContext = ProfileActivity.this;
private ProgressBar mProgressBar;
private ImageView profilePhoto;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
setupBottomNavigationView();
setupToolbar();
setupActivityWidgets();
setProfileImage();
}
private void setProfileImage(){
String imgURL = "www.androidzone.org/wp-content/uploads/2013/02/android-musical2.jpg";
UniversalImageLoader.setImage( imgURL, profilePhoto, mProgressBar, "https://");
}
private void setupActivityWidgets(){
mProgressBar = findViewById(R.id.profileProgressBar);
mProgressBar.setVisibility(View.GONE);
profilePhoto = findViewById(R.id.profile_photo);
}
private void setupToolbar() {
Toolbar toolbar = findViewById(R.id.profileToolBar);
setSupportActionBar(toolbar);
ImageView profileMenu = findViewById(R.id.profileMenu);
profileMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext, AccountSettingsActivity.class);
startActivity(intent);
}
});
}
/**
* BottomNavigationView setup
*/
private void setupBottomNavigationView() {
BottomNavigationViewEx bottomNavigationViewEx = findViewById(R.id.bottomNavViewBar);
BottomNavigationViewHelper.bottomNavigationView(bottomNavigationViewEx);
BottomNavigationViewHelper.enableNavigation(mContext, bottomNavigationViewEx);
Menu menu = bottomNavigationViewEx.getMenu();
MenuItem menuItem = menu.getItem(ACTIVITY_NUM);
menuItem.setChecked(true);
}
}
You must check that all the views that you are getting using findViewById() really exist into the activity_profile.xml layout.
One or more views doesn´t really exist, and you have a null value gettin the reference.
findViewById(R.id.profileProgressBar);
findViewById(R.id.profile_photo);
findViewById(R.id.profileToolBar);
findViewById(R.id.profileMenu);
findViewById(R.id.bottomNavViewBar);
initially you are not getting any error tryin to find the references of this views because they are really exist but in another layout but not in activity_profile.xml that you are loading via setContentView() in your Activity.
This type of exception rise at the time of the wrong variable declaration and
initialization.
Try this
replace your weighs declare and initialize val with var.
If you have to use java
final TextView helloTextView = (TextView)findViewById(R.id.text_view_id);
For Kotlin
val helloTextView = findViewById(R.id.text_view_id) as TextView
you can refer this link for more details

AppBar tabs on click listener

I have a tabbed activity with fragments.
The number of tabs is generate from the default code bellow:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 4 total pages.
return 6;
}
}
I have add icons on my tabs with the code bellow:
private int[] tabIcons = {
R.drawable.web,
R.drawable.social,
R.drawable.contact,
R.drawable.partners,
R.drawable.exclusivevideo,
R.drawable.jobifyblack
};
And inside onCreate(Bundle savedInstanceState) i am using the code bellow:
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(container);
mViewPager.setAdapter(mSectionsPagerAdapter);
//Add icons on tabs
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);
tabLayout.getTabAt(3).setIcon(tabIcons[3]);
tabLayout.getTabAt(4).setIcon(tabIcons[4]);
tabLayout.getTabAt(5).setIcon(tabIcons[5]);
By default all tabs are generated inside AppBarLayout.
Now the only thing that i want is how to trigger a click on last tab to open a new activity and do not open fragment inside container.
I tried a lot of examples without any luck!
http://www.mkyong.com/android/android-tablayout-example/
Try this example if you are not looking this please comment

Activity switch and Async Android

I have 2 activities: MainActivity which is associated with main.xml layout (app "Home" screen) and AboutActivity which is associated with about.xml layout (app "About" screen).
While in AboutActivity, an Async task within MainActivity still tries to access main.xml. My app to stop working as a result.
Is there any way I can?
"pause" the Async task within MainActivity and "resume" them when
the user switches back from AboutActivity
or still access main.xml in the background while in AboutActivity
Additional information:
MainActivity is the launch activity. AboutActivity extends MainActivity. Users can go to "About" screen/ switch to AboutActivity using the option menu.
The Async task within MainActivity put the user's current location into a textview. about.xml only contains static text. AboutActivity does nothing but show about.xml.
AboutActivity:
public class AboutActivity extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about);
}
}
MainActivity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Creating a new non-ui thread task to download Google place json data
PlacesTask placesTask = new PlacesTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
}
/** A class, to download Google Places */
private class PlacesTask extends AsyncTask<String, Integer, String>{
String data = null;
// Invoked by execute() method of this object
#Override
protected String doInBackground(String... url) {
//make asynctask wait for debugger
//android.os.Debug.waitForDebugger();
try{
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d(DEBUG,e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result){
TextView curLoc = (TextView) findViewById(R.id.CurrentLocation);
curLoc.setText(result);
}
}
}
AsyncTask not pause so we can store the data temporary when task complete and while start background activity than show data on textView.
I've solved the problem. It was a partly a variable scope problem and partly due the fact that I cannot use findViewById() there, it always return null
curLoc is null in onPostExecute in the AsyncTask.
I removed the following:
TextView curLoc = (TextView) findViewById(R.id.CurrentLocation);
and declared curLoc as a attribute of the class MainActivity
private TextView curLoc;
and also put in onCreate()
curLoc = (TextView) findViewById(R.id.CurrentLocation);

SherlockFragmentActivity with SherlockListFragment

I have 3 tabs and all of them has lists inside(different ones of course). When i click on tab I see the proper result(result which i would like to get).
I know how to get the clicked item info and make request to database about that item and get result and create new intent and put that result in it as a extra. BUT i don't know how I can display my result inside the same fragment without creating new intent. Because when i create new intent and show result in new intent my tabs obviously disappears, but i need them always to be there.
My main activity:
public class MainActivity extends SherlockFragmentActivity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(true);
Tab tab = actionBar.newTab()
.setText("Dictionary")
.setTabListener(new DictionaryFragment())
.setIcon(R.drawable.android);
actionBar.addTab(tab);
tab = actionBar.newTab()
.setText("Play")
.setTabListener(new PlayFragment())
.setIcon(R.drawable.apple);
actionBar.addTab(tab);
tab = actionBar.newTab()
.setText("Manage")
.setTabListener(new ManageFragment())
.setIcon(R.drawable.apple);
actionBar.addTab(tab);
}
}
One of my fragments:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
built_in_DB_setup dbOpenHelper = new built_in_DB_setup(getActivity().getBaseContext(), DB_NAME);
database = dbOpenHelper.openDataBase();
fillFreinds();
ArrayAdapter<String> adapter = new
ArrayAdapter<String>(getActivity().getBaseContext(), android.R.layout.simple_expandable_list_item_1, friends);
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
And here is the item click listener inside this class
public void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
String a=getData(((TextView) v).getText().toString());
Intent i = new Intent("com.example.fragmenttest.VIEWWORD");
i.putExtra("result", a);
startActivity(i);
}
Ones I have String a which i have got from onListItemClick how can I replace current Tab data with this string?

Resources