Android app, dynamic activity window with buttons - java

I am stuck with an idea.
I am trying to implement a feature in a android application.
I have an edittext and a button, if I enter 3 in edittext
and press the button I want to go to another activity which will be having 3 buttons.
If i enter 10 I wanna go to another activity where to display 10 buttons.
I know how to make such switch, I don't know how to do it dynamically ,
I want to make for values between 0 and 10 and I don't want to have 10 fragments .
Plaese give me solution to achieve it ..
Thanks..
Untill now:
mainactivity.java:
package com.example.instances_temperature;
import com.example.instances_temperature.Tabel;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
EditText instances;
Button ok;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ok = (Button) findViewById(R.id.ok);
instances = (EditText) findViewById(R.id.instances);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (instances.getText().toString().length() > 0)
{
int value = Integer.parseInt(instances.getText().toString());;
if(value > 10)
Toast.makeText(getApplicationContext(), "Enter a value between 0 and 10!", Toast.LENGTH_SHORT).show();
else
if(value<0)
Toast.makeText(getApplicationContext(), "Enter a value between 0 and 10!", Toast.LENGTH_SHORT).show();
else
if(value >= 0 && value <=10)
{
schimba(v);
}
}
else
{
Toast.makeText(getApplicationContext(), "Enter a value between 0 and 10!", Toast.LENGTH_SHORT).show();
}
}
});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#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;
}
#Override
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.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
public void schimba(View view){
int value = Integer.parseInt(instances.getText().toString());;
Intent intent = new Intent(this, Tabel.class);
intent.putExtra("max", value);
startActivity(intent);
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.instances_temperature.MainActivity"
tools:ignore="MergeRootFrame" >
<TextView
android:id="#+id/ShowValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="139dp"
android:text="Instances No.:"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/instances"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10"
android:inputType="number" >
<requestFocus />
</EditText>
<Button
android:id="#+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/instances"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:text="Ok"
android:onClick="schimba" />
</RelativeLayout>
tabel.java:
package com.example.instances_temperature;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.os.Build;
public class Tabel extends ActionBarActivity {
int i;
int value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabel);
Intent intentObject = getIntent();
value = intentObject.getIntExtra("max", 0);
LinearLayout layout = (LinearLayout)findViewById(R.id.container);
for(i=1;i<=value;i++)
{
LayoutInflater layoutinflate = null;
layoutinflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowview = layoutinflate.inflate( R.layout.ShowMe, null);
TextView showvalue;
showvalue = (TextView) rowview.findViewById(R.id.showid);
showvalue.setText(""+value);
layout.addView(rowview);
}
//showvalue.setText(String.valueOf(getIntent().getExtras().getInt("max")));
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tabel, menu);
return true;
}
#Override
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.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tabel,
container, false);
return rootView;
}
}
}
activity_tabel.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.instances_temperature.Tabel"
tools:ignore="MergeRootFrame" >
</LinearLayout>
LinearLayout code of inflation_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/inflationn"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/ShowMe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
LogCat error:
04-24 06:21:04.244: E/AndroidRuntime(269): FATAL EXCEPTION: main
04-24 06:21:04.244: E/AndroidRuntime(269): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.instances_temperature/com.example.instances_temperature.Tabel}: java.lang.NullPointerException
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.os.Handler.dispatchMessage(Handler.java:99)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.os.Looper.loop(Looper.java:123)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread.main(ActivityThread.java:4627)
04-24 06:21:04.244: E/AndroidRuntime(269): at java.lang.reflect.Method.invokeNative(Native Method)
04-24 06:21:04.244: E/AndroidRuntime(269): at java.lang.reflect.Method.invoke(Method.java:521)
04-24 06:21:04.244: E/AndroidRuntime(269): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-24 06:21:04.244: E/AndroidRuntime(269): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-24 06:21:04.244: E/AndroidRuntime(269): at dalvik.system.NativeStart.main(Native Method)
04-24 06:21:04.244: E/AndroidRuntime(269): Caused by: java.lang.NullPointerException
04-24 06:21:04.244: E/AndroidRuntime(269): at com.example.instances_temperature.Tabel.onCreate(Tabel.java:42)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-24 06:21:04.244: E/AndroidRuntime(269): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
04-24 06:21:04.244: E/AndroidRuntime(269): ... 11 more

You can get the value from the editText by...
String value= EditText.getText().toString();
Pass the value to another activity (Activity2) through Intent
Now in Activity2 you write this code in the onCreate()
for(int i=1 ; i<= value ; i++){
Button b = new Button(getApplicationContext());
LinearLayout.addView(b);
}

Answer to your edited question.....
main xml file activity_table:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
</LinearLayout>
layout file to be inflated layout_inflate:
<?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" >
<TextView
android:id="#+id/ShowValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text" />
</LinearLayout>
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabel);
Intent intentObject = getIntent();
value = intentObject.getIntExtra("max", 0);
LinearLayout layout= (LinearLayout)findViewById(R.id.layout)
for(i=0;i<=value;i++)
{
LayoutInflater layoutinflate = null;
layoutinflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowview = layoutinflate.inflate( R.layout.layout_inflate, null);
TextView showvalue;
showvalue = (TextView) rowview.findViewById(R.id.ShowValue);
showvalue.setText(""+value);
layout.addView(rowview);
}

You can retrieve the EditText value on tha Button click. And pass the Value with the intent.
In that Activity you can build your logic Using Swicth cases. Then you can add the number of Buttons dynamically (eg:- for(i=0;i<yourValue;i++) yourValue is got From intent.)

Related

Does scrollview work in fragments?

I have an employeeList fragment which upon access crashes the app. There are no squiggly lines in code, neither any alarms in the stack trace. I have a hunch that scrollView might be causing this. Here's the code
ManageFragment.java
package com.teslaqubitsins.fasih.teslahcm;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
import static android.content.Context.MODE_PRIVATE;
import static android.database.sqlite.SQLiteDatabase.openOrCreateDatabase;
public class ManageFragment extends Fragment {
EmployeeDatasource mEmployeeDatasource;
View rootView;
public ManageFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
rootView = inflater.inflate(R.layout.fragment_manage, container, false);
mEmployeeDatasource = new EmployeeDatasource(getActivity());
final ArrayList<Employee> employeeArrayList = mEmployeeDatasource.getList();
ListView mListView = (ListView) getActivity().findViewById(R.id.employeeList_listView);
EmployeeAdapter mEmployeeAdapter = new EmployeeAdapter(this.getActivity(), R.layout.row_employee_list, employeeArrayList);
mListView.setAdapter(mEmployeeAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
EmployeeDetailFragment detailedemployee = new EmployeeDetailFragment();
Employee item = employeeArrayList.get(i);
EmployeeDetailFragment.mEmployee = item;
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content, detailedemployee);
ft.addToBackStack(null);
ft.commit();
}
});
return rootView;
}
}
fragment_manage.xml
<FrameLayout 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="com.teslaqubitsins.fasih.teslahcm.ManageFragment">
<!-- TODO: Update blank fragment layout -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/employeeList_listView"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
</FrameLayout>
row_employee_list.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="2dp">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="7"
android:orientation="vertical">
<ImageView
android:id="#+id/row_employee_imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:src="#drawable/ic_stub" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="3"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="#+id/row_employee_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:maxLines="1"
android:text="Employee Name"
android:textSize="20sp" />
<TextView
android:id="#+id/row_employee_salary"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:maxLines="1"
android:text="120 PKR" />
</LinearLayout>
</LinearLayout>
</FrameLayout>
Please someone help me sort out the issue.
LOGS
04-24 15:17:31.223 1314: 1314 E/ ] Couldn't opendir /data/app/vmdl1759858640.tmp: No such file or
directory 04-24 15:17:32.773 2184-2184/com.google.android.googlequicksearchbox:search W/LocationOracle: Starting background requests 04-24 15:17:33.123 2048-2298/com.google.android.gms.persistent W/GCoreFlp: No location to return for getLastLocation() 04-24 15:17:33.124 2048-2298/com.google.android.gms.persistent W/GCoreFlp: No location to return for getLastLocation() 04-24 15:17:35.478 2048-2960/com.google.android.gms.persistent I/GCoreUlr: Starting service, intent=Intent { act=com.google.android.location.reporting.ACTION_UPDATE_WORLD cmp=com.google.android.gms/com.google.android.location.reporting.service.DispatchingService (has extras) }, extras=Bundle[{receiverAction=android.intent.action.BOOT_COMPLETED}] 04-24 15:17:36.013 2048-2986/com.google.android.gms.persistent I/GCoreUlr: WorldUpdater received intent Intent { act=com.google.android.location.reporting.ACTION_UPDATE_WORLD cmp=com.google.android.gms/com.google.android.location.reporting.service.DispatchingService (has extras) } with receiverAction android.intent.action.BOOT_COMPLETED 04-24 15:17:36.533 2048-2990/com.google.android.gms.persistent I/GCoreUlr: Starting service, intent=Intent { act=com.google.android.location.reporting.ACTION_UPDATE_WORLD cmp=com.google.android.gms/com.google.android.location.reporting.service.DispatchingService (has extras) }, extras=Bundle[{receiverAction=com.google.android.location.internal.server.ACTION_RESTARTED}] 04-24 15:17:36.575 2048-2365/com.google.android.gms.persistent I/GCoreUlr: Starting service, intent=Intent { act=com.google.android.location.reporting.ACTION_UPDATE_WORLD cmp=com.google.android.gms/com.google.android.location.reporting.service.DispatchingService (has extras) }, extras=Bundle[{receiverAction=com.google.android.location.reporting.PHENOTYPE_FLAGS_CHANGED}] 04-24 15:17:37.325 3106-3106/? W/dex2oat: /system/bin/dex2oat
--runtime-arg -classpath --runtime-arg & --instruction-set=x86 --instruction-set-features=smp,ssse3,-sse4.1,-sse4.2,-avx,-avx2,-lock_add,-popcnt
--runtime-arg -Xrelocate --boot-image=/system/framework/boot.art --runtime-arg -Xms64m --runtime-arg -Xmx512m --instruction-set-variant=x86 --instruction-set-features=default --dex-file=/data/user/0/com.google.android.gms/app_fb/f.apk --oat-fd=51 --oat-location=/data/user/0/com.google.android.gms/app_fb/f.dex --compiler-filter=speed 04-24 15:17:37.325 3106-3106/? I/dex2oat: /system/bin/dex2oat
--dex-file=/data/user/0/com.google.android.gms/app_fb/f.apk --oat-fd=51 --oat-location=/data/user/0/com.google.android.gms/app_fb/f.dex --compiler-filter=speed 04-24 15:17:37.780 2048-2298/com.google.android.gms.persistent W/GCoreFlp: No location to return for getLastLocation() 04-24 15:17:37.780 2048-2298/com.google.android.gms.persistent W/GCoreFlp: No location to return for getLastLocation() 04-24 15:17:37.920 2048-2986/com.google.android.gms.persistent I/GCoreUlr: GMS FLP location and AR updates requested: {"description":"stationary","newRequest":true,"samplePeriodMs":2160000,"sampleReason":"stationary","sampleSource":"internal","timestampMs":1493029056848} 04-24 15:17:38.057 2048-2986/com.google.android.gms.persistent I/GCoreUlr: WorldUpdater received intent Intent { act=com.google.android.location.reporting.ACTION_UPDATE_WORLD cmp=com.google.android.gms/com.google.android.location.reporting.service.DispatchingService (has extras) } with receiverAction com.google.android.location.internal.server.ACTION_RESTARTED 04-24 15:17:38.064 2048-2986/com.google.android.gms.persistent I/GCoreUlr: WorldUpdater:com.google.android.location.internal.server.ACTION_RESTARTED: Ensuring that reporting is active for [account#7#] 04-24 15:17:38.069 2048-2986/com.google.android.gms.persistent I/GCoreUlr: WorldUpdater received intent Intent { act=com.google.android.location.reporting.ACTION_UPDATE_WORLD cmp=com.google.android.gms/com.google.android.location.reporting.service.DispatchingService (has extras) } with receiverAction com.google.android.location.reporting.PHENOTYPE_FLAGS_CHANGED 04-24 15:17:38.103 2048-2986/com.google.android.gms.persistent I/GCoreUlr: WorldUpdater:com.google.android.location.reporting.PHENOTYPE_FLAGS_CHANGED: Ensuring that reporting is active for [account#7#] 04-24 15:17:38.430 2048-2048/com.google.android.gms.persistent E/ActivityThread: Service com.google.android.location.places.service.PlaceDetectionAsyncService has leaked IntentReceiver amth#cd0bee8 that was originally registered here. Are you missing a call to unregisterReceiver()?
android.app.IntentReceiverLeaked: Service com.google.android.location.places.service.PlaceDetectionAsyncService has leaked IntentReceiver amth#cd0bee8 that was originally registered here. Are you missing a call to unregisterReceiver()?
at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:1159)
at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:946)
at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1302)
at android.app.ContextImpl.registerReceiver(ContextImpl.java:1282)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:593)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:593)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:593)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:593)
at amrb.run(:com.google.android.gms:4414)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.os.HandlerThread.run(HandlerThread.java:61) 04-24 15:17:38.545 2048-2048/com.google.android.gms.persistent E/ActivityThread: Service com.google.android.location.places.service.PlaceDetectionAsyncService has leaked IntentReceiver amth#b6a0290 that was originally registered here. Are you missing a call to unregisterReceiver()?
android.app.IntentReceiverLeaked: Service com.google.android.location.places.service.PlaceDetectionAsyncService has leaked IntentReceiver amth#b6a0290 that was originally registered here. Are you missing a call to unregisterReceiver()?
at android.app.LoadedApk$ReceiverDispatcher.<init>(LoadedApk.java:1159)
at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:946)
at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1302)
at android.app.ContextImpl.registerReceiver(ContextImpl.java:1282)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:593)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:593)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:593)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:593)
at amrb.run(:com.google.android.gms:4414)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.os.HandlerThread.run(HandlerThread.java:61) 04-24 15:17:42.411 2048-2298/com.google.android.gms.persistent W/GCoreFlp: No location to return for getLastLocation() 04-24 15:17:42.411 2048-2298/com.google.android.gms.persistent W/GCoreFlp: No location to return for getLastLocation()
MainActivity.java
package com.teslaqubitsins.fasih.teslahcm;
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.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView mTextMessage;
private static final String TAG = MainActivity.class.getSimpleName();
private BottomNavigationView bottomNavigation;
private Fragment fragment;
private FragmentManager fragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
bottomNavigation = (BottomNavigationView)findViewById(R.id.navigation1);
bottomNavigation.inflateMenu(R.menu.menu);
fragmentManager = getSupportFragmentManager();
bottomNavigation.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.bb_menu_home:
fragment = new HomeFragment();
break;
case R.id.bb_menu_contact:
fragment = new ContactFragment();
break;
case R.id.bb_menu_manage:
fragment = new ManageFragment();
break;
case R.id.bb_menu_queries:
fragment = new QueriesFragment();
break;
case R.id.bb_menu_careers:
fragment = new CareersFragment();
break;
default:
fragment = new HomeFragment();
}
final FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.content, fragment).commit();
return true;
}
});
}
}
Replace:
FragmentTransaction ft = getFragmentManager().beginTransaction();
With:
FragmentTransaction ft = getChildFragmentManager().beginTransaction();

Error java.lang.runtimeexception view is not a sliding drawer

Hi I have been creating an app that implements a cutom sliding navigation drawer. However, I keep on receiving an error shown on the title.
Logs:
10-30 15:38:20.510: E/AndroidRuntime(1863): FATAL EXCEPTION: main
10-30 15:38:20.510: E/AndroidRuntime(1863): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mobextph.krispykreme/com.mobextph.krispykreme.ParentActivity}: java.lang.IllegalArgumentException: View android.widget.LinearLayout{5321e6b8 V.E..... ......ID 0,0-0,0 #7f090002 app:id/left_drawer} is not a sliding drawer
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.os.Handler.dispatchMessage(Handler.java:99)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.os.Looper.loop(Looper.java:137)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.main(ActivityThread.java:5041)
10-30 15:38:20.510: E/AndroidRuntime(1863): at java.lang.reflect.Method.invokeNative(Native Method)
10-30 15:38:20.510: E/AndroidRuntime(1863): at java.lang.reflect.Method.invoke(Method.java:511)
10-30 15:38:20.510: E/AndroidRuntime(1863): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
10-30 15:38:20.510: E/AndroidRuntime(1863): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
10-30 15:38:20.510: E/AndroidRuntime(1863): at dalvik.system.NativeStart.main(Native Method)
10-30 15:38:20.510: E/AndroidRuntime(1863): Caused by: java.lang.IllegalArgumentException: View android.widget.LinearLayout{5321e6b8 V.E..... ......ID 0,0-0,0 #7f090002 app:id/left_drawer} is not a sliding drawer
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.support.v4.widget.DrawerLayout.closeDrawer(DrawerLayout.java:1170)
10-30 15:38:20.510: E/AndroidRuntime(1863): at com.mobextph.krispykreme.ParentActivity.changeFragment(ParentActivity.java:141)
10-30 15:38:20.510: E/AndroidRuntime(1863): at com.mobextph.krispykreme.ParentActivity.onCreate(ParentActivity.java:111)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.Activity.performCreate(Activity.java:5104)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
10-30 15:38:20.510: E/AndroidRuntime(1863): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
The Main Activity class is:
package com.mobextph.krispykreme;
import java.util.ArrayList;
import com.mobextph.krispykreme.constants.Constants;
import android.R.color;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
public class ParentActivity extends FragmentActivity {
private Fragment changedFragment= null;
private FragmentManager fm;
private DrawerLayout mDrawerLayout;
private LinearLayout linearLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private ArrayList<String> navDrawerItems;
private ArrayAdapter<String> adapter;
private String[] menuItem= {"ORDER", "STAMP CARD", "REWARDS", "STORES", "FAVORITES"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Drawable d;
// getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
/*Slider*/
mTitle = mDrawerTitle = getTitle();
navMenuTitles= menuItem;
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
linearLayout = (LinearLayout) findViewById(R.id.left_drawer);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, R.id.title, menuItem));
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.button_menu, //nav menu toggle icon
R.string.app_name, // nav drawer open - description for accessibility
R.string.app_name // nav drawer close - description for accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
// changeFragment(-1);
}
fm = getSupportFragmentManager();
// DatabaseHandler db= new DatabaseHandler(this);
//
// for(int i = 0; i < 2; i++){
// db.insertFavorite(Constants.id[i], Constants.imageItem[i],
// Constants.title[i], Constants.price[i], Constants.desc[i],
// Constants.status[i]);
// }
changeFragment(-1);
}
public void changeFragment(int fragment){
FragmentTransaction transaction = fm.beginTransaction();
changedFragment = null;
switch(fragment){
case -1:
changedFragment = new HomeFragment();
// mDrawerLayout.closeDrawers();
break;
case Constants.ORDER_SCREEN_CLICKED:
changedFragment = new OrderFragment();
break;
case Constants.FAVORITES_SCREEN_CLICKED:
changedFragment = new FavoritesFragment();
break;
}
if (changedFragment != null) {
transaction.replace(R.id.fragment_holder, changedFragment);
transaction
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
transaction.addToBackStack(null);
transaction.commit();
mDrawerList.setItemChecked(fragment, true);
mDrawerList.setSelection(fragment);
mDrawerLayout.closeDrawer(linearLayout);
}
}
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// display view for selected nav drawer item
int fragment = 0;
if(position == 0)
fragment= Constants.ORDER_SCREEN_CLICKED;
else if(position == 4)
fragment= Constants.FAVORITES_SCREEN_CLICKED;
changeFragment(fragment);
}
}
// #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;
// }
//
#Override
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.
// int id = item.getItemId();
// if (id == R.id.action_settings) {
// return true;
// }
// return super.onOptionsItemSelected(item);
if(mDrawerToggle.onOptionsItemSelected(item))
return true;
switch(item.getItemId()){
default: return super.onOptionsItemSelected(item);
}
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
The view code that shows a linear layout for the sliding drawer and a listview is:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<FrameLayout
android:id="#+id/fragment_holder"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="#+id/left_drawer"
android:layout_width="260dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#008265"
android:gravity= "left" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:src="#drawable/icon_login"/>
<TextView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center"
android:text="LOGIN"
android:textSize="15dp"
android:paddingLeft="5dp"
android:paddingRight="0dp"/>
<TextView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center"
android:text="|"
android:gravity="center"
android:textSize="15dp"/>
<TextView
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center"
android:text="SIGN UP"
android:textSize="15dp"
android:paddingLeft="0dp"
android:paddingRight="5dp"/>
</LinearLayout>
<ListView
android:id="#+id/list_slidermenu"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#color/list_divider"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector"
android:gravity= "left" />
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
Try setting
layout_gravity="start" or layout_gravity="left"
in your left_drawer instead of gravity

Button causing app crash on launch

Hi when I launch my app it crashes instantly reading the logcat I can see that it is cause by the sendButton in my mainActivity, from reading around I people say it has to do with the button not being initiated but as far I can see it is, I have it declared in my fragment_main.xml okay and without the button code in MainActivity.java my code loads the app grand. Any help would really be appreciate.
Logcat
06-20 08:50:18.323: E/AndroidRuntime(30036): FATAL EXCEPTION: main
06-20 08:50:18.323: E/AndroidRuntime(30036): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.draco.dragonmessage/com.draco.dragonmessage.MainActivity}: java.lang.NullPointerException
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2483)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2535)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.ActivityThread.access$600(ActivityThread.java:178)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1390)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.os.Handler.dispatchMessage(Handler.java:107)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.os.Looper.loop(Looper.java:194)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.ActivityThread.main(ActivityThread.java:5560)
06-20 08:50:18.323: E/AndroidRuntime(30036): at java.lang.reflect.Method.invokeNative(Native Method)
06-20 08:50:18.323: E/AndroidRuntime(30036): at java.lang.reflect.Method.invoke(Method.java:525)
06-20 08:50:18.323: E/AndroidRuntime(30036): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
06-20 08:50:18.323: E/AndroidRuntime(30036): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:611)
06-20 08:50:18.323: E/AndroidRuntime(30036): at dalvik.system.NativeStart.main(Native Method)
06-20 08:50:18.323: E/AndroidRuntime(30036): Caused by: java.lang.NullPointerException
06-20 08:50:18.323: E/AndroidRuntime(30036): at com.draco.dragonmessage.MainActivity.onCreate(MainActivity.java:48)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.Activity.performCreate(Activity.java:5135)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1151)
06-20 08:50:18.323: E/AndroidRuntime(30036): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2437)
06-20 08:50:18.323: E/AndroidRuntime(30036): ... 11 more
MainActivity.java
package com.draco.dragonmessage;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;
public class MainActivity extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
String sendMessageString = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
final Button sendMessage = (Button) findViewById(R.id.messageButton);
System.out.println(sendMessage.toString());
sendMessage.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view) {
final TextView receivedMessage = (TextView) findViewById(R.id.textReceived);
final EditText messageToSend = (EditText) findViewById(R.id.editTextSend);
sendMessageString = messageToSend.toString();
receivedMessage.setText(sendMessageString);
}
});
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
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.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
fragment_main.xml
<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: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="com.draco.dragonmessage.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="#+id/editTextSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/section_label"
android:layout_alignParentBottom="true"
android:ems="10"
android:hint="Enter message to send..." />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/section_label"
android:layout_alignTop="#+id/textReceived"
android:text="Keith"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textReceived"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/section_label"
android:layout_alignRight="#+id/editTextSend"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:id="#+id/messageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/editTextSend"
android:layout_alignParentRight="true"
android:layout_marginRight="31dp"
android:text="Button" />
</RelativeLayout>
activity_main.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.draco.dragonmessage.MainActivity" >
<!--
As the main content view, the view below consumes the entire
space available using match_parent in both dimensions.
-->
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!--
android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead.
-->
<!--
The drawer is given a fixed width in dp and extends the full height of
the container.
-->
<fragment
android:id="#+id/navigation_drawer"
android:name="com.draco.dragonmessage.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start" />
</android.support.v4.widget.DrawerLayout>
Thanks again for any help.
The Button with ID messageButton is in fragment_main.xml. With findByViewById() you are accessing to activity_main.xml (setContentView(R.layout.activity_main);.
You can add an attribute Button to the class and link the element in the onCreateView method of PlaceholderFragment. Then you can access to this button from anywhere in the activity.
Just Move the following lines to Oncreate() and change R.layout to your fragment layout. You are using a wrong layout
final TextView receivedMessage = (TextView) findViewById(R.id.textReceived);
final EditText messageToSend = (EditText) findViewById(R.id.editTextSend);
below this one
final Button sendMessage = (Button) findViewById(R.id.messageButton);

Android Text View giving an error when trying to set text

I have a layout with few labels and textviews which I want to update based on a action. For testing I have set up the java MainActivity to load the textviews I want to use on created.
Once I click a button called add, the code is executed and prints that the add button was pushed.
I also want the text area to say add for testing. Later on in the project I will change what is displayed here.
However, once I click the button the program stops. I know that the button works because the print shows up in the log.
I have looked and looked and all I can find is the textfield.settext(); But when using this the error occurs and the program stops.
Below is my XML for the TextView:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android1="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000066"
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="com.example.smartshop.MainActivity$PlaceholderFragment" >
<LinearLayout
android1:id="#+id/linearLayout1"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:orientation="vertical" >
<ListView
android1:id="#+id/cartlist"
android1:layout_width="289dp"
android1:layout_height="236dp"
android1:textColor="#color/textc" >
</ListView>
<LinearLayout
android1:layout_width="match_parent"
android1:layout_height="wrap_content" >
<Button
android1:id="#+id/btnadd"
android1:layout_width="0pt"
android1:layout_height="wrap_content"
android1:layout_weight="1"
android1:background="#color/buttonc"
android1:onClick="clkaddbutton"
android1:text="Add Item" />
<!-- android1:onClick="clkaddbutton" -->
<android.support.v7.widget.Space
android1:id="#+id/space1"
android1:layout_width="2dp"
android1:layout_height="wrap_content" />
<Button
android1:id="#+id/btnremove"
android1:layout_width="0pt"
android1:layout_height="wrap_content"
android1:layout_weight="1"
android1:background="#color/buttonc"
android1:onClick="clkremovebutton"
android1:text="Remove Item" />
<!-- android1:onClick = "clkremovebutton" -->
</LinearLayout>
<View
android:layout_width="1dp"
android:layout_height="#dimen/verticalspacesize">
</View>
<LinearLayout
android1:layout_width="match_parent"
android1:layout_height="wrap_content" >
<TextView
android1:id="#+id/lblsubtotal"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_weight="3.40"
android1:text="Sub Total"
android1:textSize="#dimen/textsize"
android1:textColor="#color/textc" />
<TextView
android1:id="#+id/tvsubtotal"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_weight="3.40"
android1:textSize="#dimen/textsize"
android1:text="TextView" />
</LinearLayout>
<View
android:layout_width="1dp"
android:layout_height="#dimen/verticalspacesize">
</View>
<LinearLayout
android1:layout_width="match_parent"
android1:layout_height="wrap_content" >
<TextView
android1:id="#+id/lbltax"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_weight="1"
android1:text="Tax"
android1:textSize="#dimen/textsize"
android1:textColor="#color/textc" />
<TextView
android1:id="#+id/tvtax"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_weight="1"
android1:textSize="#dimen/textsize"
android1:text="TextView" />
</LinearLayout>
<View
android:layout_width="1dp"
android:layout_height="#dimen/verticalspacesize">
</View>
<LinearLayout
android1:layout_width="match_parent"
android1:layout_height="wrap_content" >
<TextView
android1:id="#+id/lbltotal"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_weight="1"
android1:text="Total"
android1:textSize="#dimen/textsize"
android1:textColor="#color/textc" />
<TextView
android1:id="#+id/tvtotal"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_weight="1"
android1:textSize="#dimen/textsize"
android1:text="TextView" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Here is the java code in the MainActivity:
package com.example.smartshop;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Build;
import java.lang.*;
public class MainActivity extends ActionBarActivity {
private Button btnadd;
private Button btnremove;
private TextView tfsubtotal ;
private TextView tftax;
private TextView tftotal;
public void clkaddbutton(View view) {
System.out.println("Add clicked");
tfsubtotal.setText("add");
}
public void clkremovebutton(View view) {
tfsubtotal.setText("Rem");
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnremove = (Button) findViewById(R.id.btnremove);
btnadd = (Button) findViewById(R.id.btnadd);
tfsubtotal = (TextView) findViewById(R.id.tvsubtotal);
if(tfsubtotal != null){
System.out.println("The subtotal edittext was created");
tfsubtotal.setText("test" );
}
else{
System.out.println("The textview is null");
}
//tfsubtotal.setText("Google is your friend." );
tftax = (TextView) findViewById(R.id.tvtax);
tftotal = (TextView) findViewById(R.id.tvtotal);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#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;
}
#Override
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.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
I know that the problem is on the tfsubtotal.setText("add"); line because I have tested without it and everything works.
I have also tried to use edit text boxes instead of textviews but I get the same error.
Can anyone suggest what I might be doing wrong?
Thank you.
Below is the android log:
05-22 22:37:21.251: I/System.out(1693): The subtotal edittext was created
05-22 22:37:21.251: D/AndroidRuntime(1693): Shutting down VM
05-22 22:37:21.261: W/dalvikvm(1693): threadid=1: thread exiting with uncaught exception (group=0xb2accba8)
05-22 22:37:21.271: E/AndroidRuntime(1693): FATAL EXCEPTION: main
05-22 22:37:21.271: E/AndroidRuntime(1693): Process: com.example.smartshop, PID: 1693
05-22 22:37:21.271: E/AndroidRuntime(1693): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.smartshop/com.example.smartshop.MainActivity}: java.lang.NullPointerException
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.ActivityThread.access$800(ActivityThread.java:135)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.os.Handler.dispatchMessage(Handler.java:102)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.os.Looper.loop(Looper.java:136)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-22 22:37:21.271: E/AndroidRuntime(1693): at java.lang.reflect.Method.invokeNative(Native Method)
05-22 22:37:21.271: E/AndroidRuntime(1693): at java.lang.reflect.Method.invoke(Method.java:515)
05-22 22:37:21.271: E/AndroidRuntime(1693): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-22 22:37:21.271: E/AndroidRuntime(1693): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-22 22:37:21.271: E/AndroidRuntime(1693): at dalvik.system.NativeStart.main(Native Method)
05-22 22:37:21.271: E/AndroidRuntime(1693): Caused by: java.lang.NullPointerException
05-22 22:37:21.271: E/AndroidRuntime(1693): at com.example.smartshop.MainActivity.onCreate(MainActivity.java:42)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.Activity.performCreate(Activity.java:5231)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
05-22 22:37:21.271: E/AndroidRuntime(1693): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
05-22 22:37:21.271: E/AndroidRuntime(1693): ... 11 more
05-22 22:37:23.451: I/Process(1693): Sending signal. PID: 1693 SIG: 9
Try this:
public class MainActivity extends ActionBarActivity {
private Button btnadd;
private Button btnremove;
private TextView tfsubtotal ;
private TextView tftax;
private TextView tftotal;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnadd = (Button) findViewById(R.id.btnadd);
System.out.println("The subtotal edittext was created");
//tfsubtotal.setText("Google is your friend." );
tftax = (TextView) findViewById(R.id.tvtax);
TextView tfsubtotal = (TextView) findViewById(R.id.tvsubtotal);
tftotal = (TextView) findViewById(R.id.tvtotal);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
public void clkaddbutton(View view) {
// tfsubtotal.
System.out.println("Add clicked");
tfsubtotal.setText("add");
}
public void clkremovebutton(View view) {
tfsubtotal.setText("Rem");
}
OR
Why not just do simply like this :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnadd = (Button) findViewById(R.id.btnadd);
Button btnRemove = (Button)findViewById(R.id.btnremove);
tfsubtotal = (TextView) findViewById(R.id.tvsubtotal);
System.out.println("The subtotal edittext was created");
//tfsubtotal.setText("Google is your friend." );
tftax = (TextView) findViewById(R.id.tvtax);
tftotal = (TextView) findViewById(R.id.tvtotal);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
btnadd.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
System.out.println("Add clicked");
tfsubtotal.setText("add");
}
});
btnRemove.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
System.out.println("Add clicked");
tfsubtotal.setText("Rem");
}
});
}

No view found for id 0x7f070053

was testing som things in Android Studios and ran in to this error:
FATAL EXCEPTION: main
Process: com.meisolsson.app, PID: 25610
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.meisolsson.app/com.meisolsson.app.LoginActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f070053 (com.meisolsson.app:id/container) for fragment PlaceholderFragment{4284e750 #0 id=0x7f070053}
Here is my LoginActivity.java
package com.meisolsson.app;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
import android.view.Window;
import android.widget.Button;
public class LoginActivity extends ActionBarActivity {
private Button loginButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_login);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
this.setContentView(R.layout.fragment_login);
this.loginButton = (Button)this.findViewById(R.id.button);
this.loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#Override
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.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_login, container, false);
return rootView;
}
}
}
And my fragment_login.xml
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".LoginActivity$PlaceholderFragment"
android:focusable="true"
android:background="#fcff00">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:hint="#string/user"
android:padding="10dp"
android:background="#ffffff"
android:layout_above="#+id/editText2"
android:layout_alignLeft="#+id/editText2"
android:layout_alignRight="#+id/editText2" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:id="#+id/editText2"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:hint="#string/pass"
android:background="#ffffff"
android:padding="10dp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/login"
android:id="#+id/button"
style="#style/AppTheme"
android:background="#ff5900"
android:shadowColor="#000000"
android:layout_below="#+id/editText2"
android:layout_alignLeft="#+id/editText"
android:layout_alignRight="#+id/editText2"
android:clickable="true"/>
</RelativeLayout>
The problem is the way you're doing this. For the Activity, you don't set the Fragment's view, you set a separate view that has a spot to put a Fragment. Depending on how you did your PlaceHolderFragment, the following ought to get a working app.
First add this file:
activity_main.xml
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Then change this stuff in your Activity:
LoginActivity.java
/* Same stuff*/
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
//This is the important change right here!
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
//The stuff that you had handling buttons should go in your
//PlaceHolderFragment class's onCreateView() method
}
I hope this helps. Good Luck!

Categories

Resources