Unable to dynamically add TextView when java class extends AppCompatActivity - java

I am trying to add a TextView dynamically to my activity, but when i run the app it is not showing up. There are no errors, and the app does not crash, but the TextView does not show up. My java class extends AppCompatActivty, and i noticed that when i change it to extending Activity my code works, and the TextView shows up. My question is, why does the following code work for Activity but not AppCompatActivity?
My java class FormActivty.java
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.LinearLayout;
import android.widget.TextView;
public class FormActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.activity_form);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.container);
TextView textView = new TextView(this);
textView.setText("Hello world");
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout.addView(textView);
}
}
My XML activity_form.xml
<?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"
android:id="#+id/formLayout">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/container"
android:orientation="vertical"></LinearLayout>
</LinearLayout>

I am not sure why this is the case, but if i remove PersistableBundle persistentState from the onCreate method, then it works. my java class now looks like
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.LinearLayout;
import android.widget.TextView;
public class FormActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.container);
TextView textView = new TextView(this);
textView.setText("Hello world");
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
linearLayout.addView(textView);
}
}

Related

My app is crashing because of the "addView": the error on it is: Method invocation may produce nullPointException

// *** See the error marked below ***
package com.example.android.miwok;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
public class NumbersActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_numbers);
ArrayList<String> words = new ArrayList<String>();
words.add(0,"One");
words.add(1, "Two");
words.add(2, "Three");
words.add(3,"Four");
words.add(4,"Five");
words.add(5,"Six");
words.add(6,"Seven");
words.add(7,"Eight");
words.add(8,"Nine");
words.add(9,"Ten");
LinearLayout rootView = (LinearLayout) findViewById(R.id.rootView);
TextView wordsView = new TextView(this);
wordsView.setText(words.get(0));
// ***
// Here is the addView method that's not working:
// ***
rootView.addView(wordsView);
}
}
I don't know why this crash is happening. When I want to test my app, it crashes and says that it has stopped and when I remove the code from "calling the linear layout" to "after the "rootView.addView(wordsView);" "
I just tested your code:
Java code:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<String> words = new ArrayList<String>();
words.add(0,"One");
words.add(1,"Two");
words.add(2,"Three");
words.add(3,"Four");
words.add(4,"Five");
words.add(5,"Six");
words.add(6,"Seven");
words.add(7,"Eight");
words.add(8,"Nine");
words.add(9,"Ten");
LinearLayout rootView = findViewById(R.id.layout);
TextView textView = new TextView(this);
textView.setText(words.get(0));
rootView.addView(textView);
}
}
XML code:
<?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"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/layout"
android:layout_width="368dp"
android:layout_height="495dp"
android:orientation="vertical"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"></LinearLayout>
</android.support.constraint.ConstraintLayout>
As you can see the code works fine for me. Also you should provide your XML.

Displaying imageslider within a fragment

I have created an ImageSlider as a new activity seperate to my main project in order to see if it worked. Well guess what, it does! The problem is it is activity based, and when I try and implement it into my other project which has fragments I get so many errors within my MainActivity. Could someone help me please? I believe the issue might be related to my main project also having a navigation drawer & a fragment within the MainActivity main page of the app.
MainActivity test project code which works:
package com.example.user1.imageslidertest;
import android.support.v4.app.FragmentManager;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
LinearLayout sliderDotspanel;
private int dotscount;
private ImageView[] dots;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.ViewPager);
sliderDotspanel = (LinearLayout) findViewById(R.id.SliderDots);
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(this);
viewPager.setAdapter(viewPagerAdapter);
dotscount = viewPagerAdapter.getCount();
dots = new ImageView[dotscount];
for(int i = 0; i < dotscount; i++){
dots[i] = new ImageView(this);
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.nonactive_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
sliderDotspanel.addView(dots[i], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for(int i = 0; i< dotscount; i++){
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.nonactive_dot));
}
dots[position].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
ViewPagerAdapter code:
package com.example.user1.imageslidertest;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class ViewPagerAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
private Integer [] images = {R.drawable.a45large, R.drawable.a45largeintior, R.drawable.a45largerear};
public ViewPagerAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return images.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.custom_layout, null);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
imageView.setImageResource(images[position]);
ViewPager vp = (ViewPager) container;
vp.addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
activity_main.xml code:
<?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"
tools:context="com.example.user1.imageslidertest.MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/ViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
<LinearLayout
android:id="#+id/SliderDots"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/ViewPager"
android:gravity="center_vertical|center_horizontal"
android:orientation="horizontal"
android:paddingTop="300dp">
</LinearLayout>
</android.support.constraint.ConstraintLayout>
custom_layout.xml code:
<?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"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="292dp"
app:srcCompat="#drawable/a45large" />
</LinearLayout>
My MainActivity from my main project with fragments and navigation drawer (where the issues are when I put the test MainActivity code in):
package com.example.user1.mainproject;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
// Code to display Home Fragment on App Launch Page
HomeFragment homeFragment = new HomeFragment();
FragmentManager manager = getSupportFragmentManager();
manager.beginTransaction().replace(
R.id.relativelayout_for_fragment,
homeFragment,
homeFragment.getTag()
).commit();
}
This is the biggest issue I've faced within my project so would really apreciate some help, thanks!

Error using relative layout using code

I am getting java.lang.IllegalStateException while using relative layout using code. I know how to use relative layout using xml, but I have to use it using code only.
Here is my code:
package com.example.pr;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnFocusChangeListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class ProfessionalProfileTab extends Fragment
{
EditText regNumber,medCouncil,languages,degree,course,year,speciality,
experience_start_month,experience_end_month,designation,experience_company;
TextView regNumberText,medCouncilText,languagesText,degreeText,specialityText,experienceText;
ImageButton addDegree;
Button updateProfession;
Display display;
double width,height;
private int mYear, mMonth, mDay;
Context con;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
display = getActivity().getWindowManager().getDefaultDisplay();
width = MainActivity.Parentwidth;
height = MainActivity.Parentheight;
Log.d("Inside Professional Profile Fragment","ppsg");
Log.d("width",String.valueOf(width));
Log.d("height",String.valueOf(height));
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
final View view = inflater.inflate(R.layout.professional_profile_tab, container, false);
con = container.getContext();
final LinearLayout layout=(LinearLayout)view.findViewById(R.id.professionalProfileDetails);
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
android.widget.LinearLayout.LayoutParams.MATCH_PARENT,
final RelativeLayout rlayout=(RelativeLayout)view.findViewById(R.id.reldegree) ;
final RelativeLayout.LayoutParams rparam=new RelativeLayout.LayoutParams(
android.widget.RelativeLayout.LayoutParams.MATCH_PARENT,
android.widget.RelativeLayout.LayoutParams.MATCH_PARENT) ;
final TextView degreeText=new TextView(con);
degreeText.setTag("degreeText");
degreeText.setText("degree:");
layout.addView(degreeText);
rlayout.addView(degreeText);
rparam.addRule(RelativeLayout.BELOW,degreeText.getId());
degreeText.setLayoutParams(params);
degreeText.setLayoutParams(rparam);
final ImageButton addDegree=new ImageButton(con);
addDegree.setTag("addDegree");
addDegree.setImageResource(R.drawable.ic_launcher);
layout.addView(addDegree);
rlayout.addView(addDegree);
rparam.addRule(RelativeLayout.BELOW,addDegree.getId());
degreeText.setLayoutParams(params);
addDegree.setLayoutParams(rparam);
return view;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_settings)
return true;
return super.onOptionsItemSelected(item);
}
}
Here is the xml version of what I want from my code:
<LinearLayout
android:id="#+id/professionalProfileDetails"
android:layout_width="320dp"
android:layout_height="200dp"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/reldegree"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/degreeText"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:text="Degree Details"/>
<ImageButton
android:id="#+id/addDegree"
android:layout_toRightOf="#id/degreeText"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/ic_launcher"/>
</RelativeLayout>
</LinearLayout>
Here I want to set the image to the right of degreetext textField.
I have tried to search for a solution to this problem, but could not find any.
Can we use relative layout in the same way as we do in xml and set layout:toRightOf or toLeftOf or below etc using code for texts or images.
You are trying to add the same View to 2 different ViewGroups which is not possible.
layout.addView(degreeText);
rlayout.addView(degreeText);
Also, you are trying to position a View below itself.
rparam.addRule(RelativeLayout.BELOW,degreeText.getId());
degreeText.setLayoutParams(rparam);
**Try this**
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.demo.MainActivity" >
<RelativeLayout
android:id="#+id/layoutContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="10dp" >
</RelativeLayout>
</RelativeLayout>
MainActivity.java
public class MainActivity extends Activity {
RelativeLayout layoutContainer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layoutContainer = (RelativeLayout)
findViewById(R.id.layoutContainer);
final TextView degreeText=new TextView(this);
degreeText.setId(1);
degreeText.setText("degree:");
layoutContainer.addView(degreeText);
RelativeLayout.LayoutParams params = new
RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.RIGHT_OF, degreeText.getId());
final ImageButton addDegree=new ImageButton(this);
addDegree.setImageResource(R.drawable.ic_launcher);
addDegree.setLayoutParams(params);
layoutContainer.addView(addDegree);
}
}

Android: Why TextField is not showing?

TextView t = new TextView(this);
t.setX(0);
t.setY(0);
t.setText("Tap");
t.setTextColor(Color.GREEN);
t.setTextSize(25);
t.setLayoutParams(new FrameLayout.LayoutParams(100, 100));
setContentView(t);
I'am in ActionBarActivity, that why I'am using "this" as context, can't understand why the textField isn't showing, is here something wrong?
Try this one
TextView t= new TextView(this);
t.setX(0);
t.setY(0);
t.setText("Tap");
t.setTextColor(Color.GREEN);
t.setTextSize(25);
addContentView(t, new FrameLayout.LayoutParams(100, 100));
Create xml file
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/frame_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="in.appkart.flashlight.MainActivity" >
</FrameLayout>
and MainActivity
package in.appkart.flashlight;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View frameLayout = findViewById(R.id.frame_layout);
TextView t = new TextView(this);
t.setX(0);
t.setY(0);
t.setText("Tap");
t.setTextColor(Color.GREEN);
t.setTextSize(25);
t.setLayoutParams(new FrameLayout.LayoutParams(100, 100));
t.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
((FrameLayout) frameLayout).addView(t);
}
}

displaying blogs in webview

I want to display my blog as a part of an android application..i have the code ready..it works well when displaying websites like google etc but not with my blog..can someone help me solve this problem
mainActivity.java:
package com.mkyong.android;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Button button;
public void onCreate(Bundle savedInstanceState) {
final Context context = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.buttonUrl);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(context, WebViewActivity.class);
startActivity(intent);
}
});
}
}
webViewActivity.java:
package com.mkyong.android;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebViewActivity extends Activity {
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.webview);
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("pavan7vasan.blogspot.com");
}
}
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/buttonUrl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go to http://www.google.com" />
</LinearLayout>
webview.xml:
<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
it shows web page not available in the android emulator
Change this line, and it should work.
webView.loadUrl("http://pavan7vasan.blogspot.com");

Categories

Resources