I'm not sure why i am getting this error, it was working before, any help is appreciated. Trying to spawn a new activity upon spinner selection ( I have a working version with a list view inside, I decided to branch off to try a spinner, got pretty far and then got lost trying to figure out this error). It was working perfectly too, so I know that i has to be like 1-5 lines of code or something. Again, any help is appreciated.
Logcat
02-19 23:57:15.980: E/AndroidRuntime(350): FATAL EXCEPTION: main
02-19 23:57:15.980: E/AndroidRuntime(350): java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.example.jordanmaxportfolio/com.example.jordanmaxportfolio.MainActivity}: java.lang.NullPointerException
02-19 23:57:15.980: E/AndroidRuntime(350): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
02-19 23:57:15.980: E/AndroidRuntime(350): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
02-19 23:57:15.980: E/AndroidRuntime(350): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-19 23:57:15.980: E/AndroidRuntime(350): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
02-19 23:57:15.980: E/AndroidRuntime(350): at android.os.Handler.dispatchMessage(Handler.java:99)
02-19 23:57:15.980: E/AndroidRuntime(350): at android.os.Looper.loop(Looper.java:123)
02-19 23:57:15.980: E/AndroidRuntime(350): at android.app.ActivityThread.main(ActivityThread.java:3683)
Main Activity
package com.example.jordanmaxportfolio;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity
implements AdapterView.OnItemSelectedListener {
TextView selection;
ListView list;
Spinner spin = (Spinner) findViewById(R.id.spinner2);
public final static String exID="com.example.portfolio.MainActivity";
static final String[] items = new String[] {
"36-2510 Game Engine Scripting I",
"36-2551 C++ I",
"36-3210 Game AI Programming",
"36-3405 Authoring Interactive Media I & II"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
list = (ListView)findViewById(R.id.listView1);
String[] items = getResources().getStringArray(R.array.Classes);
list.setAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,items));
list.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view,
int postion, long id){
Intent i =new Intent(MainActivity.this,ClassPage.class);
i.putExtra(exID, String.valueOf(id));
startActivity(i);
}
});
selection = (TextView) findViewById(R.id.textView1);
Spinner spin = (Spinner) findViewById(R.id.spinner2);
spin.setOnItemSelectedListener(this);
ArrayAdapter<String> aa = new ArrayAdapter<String>(
this,
android.R.layout.simple_spinner_item,
items);
aa.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(aa);
}
#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;
}
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
selection.setText(items[position]);
Intent i =new Intent(MainActivity.this,ClassPage.class);
i.putExtra(exID, String.valueOf(position));
startActivity(i);
}
/*spin.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
Intent i =new Intent(MainActivity.this,ClassPage.class);
i.putExtra(exID, String.valueOf(id));
startActivity(i);
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
}
});*/
/* example I saw online, however not quite right */
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
selection.setText("");
}
}
ClassPage
package com.example.jordanmaxportfolio;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
public class ClassPage extends Activity {
private TextView passedView = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_class);
String passedVar = getIntent().getStringExtra(MainActivity.exID);
passedView = (TextView)findViewById(R.id.tv1);
//passedView.setText("You have clicked item id: "+passedVar);
if(passedVar.equals("0"))
{
passedView.setText("YAYY");
}
if(passedVar.equals("1"))
{
passedView.setText("Game Engine Scripting I");
ImageView iv = (ImageView)findViewById(R.id.imageView1);
iv.setImageResource(R.drawable.asteroids);
TextView tv2 = (TextView)findViewById(R.id.tv2);
tv2.setText("Using C# and Unity, I created a remake of the classic 'Asteroids!'. Dynamic difficulty level is the next addition.");
}
else if(passedVar.equals("2"))
{
passedView.setText("C++ I");
ImageView iv = (ImageView)findViewById(R.id.imageView1);
iv.setImageResource(R.drawable.poker);
TextView tv2 = (TextView)findViewById(R.id.tv2);
tv2.setText("Console GUI C++ Texas Hole 'Em Poker created by Neil Inglese and Jordan Max. Basic concept of game was to eliminate cursors. The game was completed, however we are re-doing it for our C++ II class to make it into the Xbox Live and Windows Store.");
}
else if(passedVar.equals("3"))
{
passedView.setText("Game AI Programming");
ImageView iv = (ImageView)findViewById(R.id.imageView1);
iv.setImageResource(R.drawable.game);
TextView tv2 = (TextView)findViewById(R.id.tv2);
tv2.setText("Currently enrolled in this class, we are learning about FSM's and C++ data structures such as stacks, vectors and queues. ");
}
else
{
passedView.setText("Authoring Interactive Media I & II");
ImageView iv = (ImageView)findViewById(R.id.imageView1);
iv.setImageResource(R.drawable.p);
TextView tv2 = (TextView)findViewById(R.id.tv2);
tv2.setText("Learned basic skills for HTML and CSS. Also divulged into HTML5, PHP, jQuery, and Javascript for web programming. Created my portfolio website based off knowledge learned.");
}
Button btn1 = (Button)findViewById(R.id.button1);
// Show the Up button in the action bar.
setupActionBar();
}
public void btnClicked(View view){
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.class_page, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
acitvity_class.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=".ClassPage" >
<TextView
android:id="#+id/tv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="#string/hello_world" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="200dp"
android:layout_alignLeft="#+id/tv1"
android:layout_alignRight="#+id/tv1"
android:layout_below="#+id/tv1"
android:layout_marginTop="46dp"
android:maxHeight="500dp"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/tv2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/imageView1"
android:layout_alignParentRight="true"
android:layout_below="#+id/imageView1"
android:layout_marginLeft="21dp"
android:layout_marginTop="60dp"
android:text="TextView" />
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/tv2"
android:layout_below="#+id/tv2"
android:layout_marginTop="20dp"
android:onClick="btnClicked"
android:text="Go Back" />
</RelativeLayout>
activity_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=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello_world" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/spinner1" >
</ListView>
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_marginTop="67dp"
android:layout_toLeftOf="#+id/listView1" />
<TextView
android:id="#+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/textView1"
android:text="#string/hello" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/textView2"
android:layout_marginLeft="57dp" />
</RelativeLayout>
Put this
Spinner spin = (Spinner) findViewById(R.id.spinner2);
Inside your onCreate() after setContentView(R.layout.activity_main);
add this
Spinner spin=(Spinner)findViewById(R.id.spinner2);
in your mainactivity.
Try this..
Do this inside OnCreate after setContentView(R.layout.activity_main); in MainActivity
Spinner spin = (Spinner) findViewById(R.id.spinner2);
OR
Remove Spinner spin = (Spinner) findViewById(R.id.spinner2); from Global variable
You are attempting to initialize the class member spin with a call to findViewById(). However, at the time your Activity class is constructed, the layout will not yet be inflated. This means you must wait until onCreate() to do this initialization. As other's have answered, you need to put spin = (Spinnder) findViewById(R.id.spinner2) in the onCreate() method after the call to setContentView().
To understand this in more detail, I strongly suggest that you read about the Activity life-cycle.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I tried creating a simple app "MemeCrater" which i learned from one of youtube tutorial.but whenever i press the Create button.The App crashes.
This is the error i get.
Error
Process: com.example.iemshekhar.memegenerator, PID: 13118
java.lang.NullPointerException: Attempt to invoke interface method 'void com.example.iemshekhar.memegenerator.TopSectionFragment$TopSectionListener.createMeme(java.lang.String, java.lang.String)' on a null object reference
at com.example.iemshekhar.memegenerator.TopSectionFragment.buttonClicked(TopSectionFragment.java:57)
at com.example.iemshekhar.memegenerator.TopSectionFragment$1.onClick(TopSectionFragment.java:49)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10815)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
This is my main activity java file:
MainActivity.java
package com.example.iemshekhar.memegenerator;
import android.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity implements TopSectionFragment.TopSectionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public void createMeme(String top, String bottom) {
BottomPictureFragment bottmfragment=(BottomPictureFragment)getFragmentManager().findFragmentById(R.id.fragment2);
bottmfragment.setMemeText(top,bottom);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is my top Fragement java file:
TopSectionFragment.java
package com.example.iemshekhar.memegenerator;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class TopSectionFragment extends Fragment {
private static EditText top, bottom;
TopSectionListener activitycommander;
public interface TopSectionListener{
public void createMeme(String top,String bottom);
}
public void onAtttach(Context context)
{
try{
activitycommander=(TopSectionListener)context;
}
catch(ClassCastException e){
throw new ClassCastException(e.getMessage());
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.top_section_fragment, container, false);
top = (EditText)view.findViewById(R.id.toptextinput);
bottom = (EditText) view.findViewById(R.id.bottomtextinput);
final Button create = (Button) view.findViewById(R.id.createbutton);
create.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
buttonClicked(v);
}
}
);
return view;
}
public void buttonClicked(View v) {
activitycommander.createMeme(top.getText().toString(),bottom.getText().toString());
}
}
This file is my bottom Fragment java File:
BottomSectionFragment.java
package com.example.iemshekhar.memegenerator;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* Created by IEmShekhar on 6/18/2016.
*/
public class BottomPictureFragment extends Fragment {
public static TextView toptext,bottomtext;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.bottom_picture_fragment, container, false);
toptext=(TextView)view.findViewById(R.id.textView1);
bottomtext=(TextView)view.findViewById(R.id.textView2);
return view;
}
public void setMemeText(String top,String bottom){
toptext.setText(top);
bottomtext.setText(bottom);
}
}
These are my XML Files:
activity_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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:background="#006669"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<fragment
android:layout_width="wrap_content"
android:layout_height="290dp"
android:name="com.example.iemshekhar.memegenerator.BottomPictureFragment"
android:id="#+id/fragment2"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
tools:layout="#layout/bottom_picture_fragment" />
<fragment
android:layout_width="400dp"
android:layout_height="wrap_content"
android:name="com.example.iemshekhar.memegenerator.TopSectionFragment"
android:id="#+id/fragment"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
tools:layout="#layout/top_section_fragment"
android:layout_above="#+id/fragment2" />
</RelativeLayout>
Top_section_Fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent" android:background="#999999">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/toptextinput"
android:layout_centerHorizontal="true"
android:layout_marginTop="15dp"
android:width="300dp"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/bottomtextinput"
android:layout_centerHorizontal="true"
android:layout_below="#+id/toptextinput"
android:width="300dp"
android:layout_marginTop="30dp"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:layout_centerHorizontal="true"
android:text="#string/Create_text"
android:background="#006666"
android:textStyle="bold"
android:id="#+id/createbutton"/>
</RelativeLayout>
Bottom_picture_Fragement.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="#drawable/afaque">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/toptext"
android:textStyle="bold"
android:textSize="25sp"
android:background="#ffff"
android:width="400dp"
android:textAlignment="center"
android:id="#+id/textView1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/bottomtext"
android:textStyle="bold"
android:textSize="25sp"
android:background="#ffff"
android:width="400dp"
android:textAlignment="center"
android:id="#+id/textView2"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
Guessing that you're trying to set the text from editText, You should be accessing the text from your editText in your TopSectionFragment
Replace
//Initialize
`private static TextView top, bottom;`
//onCreateView() Method
top = (TextView) view.findViewById(R.id.textView1);
bottom = (TextView) view.findViewById(R.id.textView2);
with this
//Initialize
`private static EditText top, bottom;`
//onCreateView Method
//onCreateView() Method
top = (EditText) view.findViewById(R.id.toptextinput);
bottom = (EditText) view.findViewById(R.id.bottomtextinput);
in your TopSectionFragment. Hope this will help :)
i wrote a toDO list for my android class. It totally works , but now i want to display the todo list on a fragment ( so it can be its on tab). but when i tried making the fragment , i get a weird error when i try to run it. apparently the error comes from my main activity . so the way i have it set up is that, my main activity has a button that opens the fragment that has all the TOdolist stuff in it. but when i run it on my phone i get a unfortunately TodoList ha stopped as soon as it runs. the error is get is
06-10 22:21:51.284 5302-5302/com.example.mike.todolist D/AbsListView﹕ Get MotionRecognitionManager
06-10 22:21:51.304 5302-5302/com.example.mike.todolist D/AndroidRuntime﹕ Shutting down VM
06-10 22:21:51.304 5302-5302/com.example.mike.todolist W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x417c2898)
06-10 22:21:51.314 5302-5302/com.example.mike.todolist E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.mike.todolist.ToDoFragment.onCreateView(ToDoFragment.java:38)
at android.app.Fragment.performCreateView(Fragment.java:1699)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:903)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1075)
at android.app.BackStackRecord.run(BackStackRecord.java:682)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1455)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:441)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5455)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1187)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
at dalvik.system.NativeStart.main(Native Method)
my main activity look like
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.view.View;
public class MainActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.todo_main_activity);
super.onCreate(savedInstanceState);
Button button1 = (Button) findViewById(R.id.fragButton);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction
=fragmentTransaction=fragmentManager.beginTransaction();
ToDoFragment fragment = new ToDoFragment();
fragmentTransaction.add(R.id.mainLL, fragment);
fragmentTransaction.commit();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return true;
}
}
My main activity xml is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:id="#+id/mainLL"
android:layout_height="fill_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="frag"
android:id="#+id/fragButton"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:onClick="fragButtonClick"
android:layout_gravity="center_horizontal" />
</LinearLayout>
Fragment.java
package com.example.mike.todolist;
import android.app.AlertDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import com.example.mike.todolist.db.Contract;
import com.example.mike.todolist.db.DBHelper;
/**
* Created by mike on 6/10/15.
*/
public class ToDoFragment extends ListFragment {
public ListAdapter listAdapter;
public DBHelper helper;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view=inflater.inflate(R.layout.fragmentlayout, container, false);
// Inflate the layout for this fragment
update();
Button doneButton = (Button)view.findViewById(R.id.doneButton);
doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
View v = (View) view.getParent();
TextView taskTextView = (TextView) v.findViewById(R.id.taskTextView);
String task = taskTextView.getText().toString();
String sql = String.format("DELETE FROM %s WHERE %s = '%s'",
Contract.TABLE_NAME,
Contract.Columns.TASK,
task);
helper = new DBHelper(getActivity());
SQLiteDatabase sqlDB = helper.getWritableDatabase();
sqlDB.execSQL(sql);
update();
}
});
Button addButton = (Button)view.findViewById(R.id.AddButton);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
switch (R.id.add_task) {
case R.id.add_task:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Add a task");
builder.setMessage("What would you like to do?");
final EditText input = new EditText(getActivity());
builder.setView(input);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String task = input.getText().toString();
helper = new DBHelper(getActivity());
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.clear();
cv.put(Contract.Columns.TASK, task);
db.insertWithOnConflict(Contract.TABLE_NAME, null, cv, SQLiteDatabase.CONFLICT_IGNORE);
update();
}
});
builder.setNegativeButton("Cancel", null);
builder.create().show();
}
}
});
return view;
}
private void update() {
helper = new DBHelper(getActivity());
SQLiteDatabase sqlDB = helper.getReadableDatabase();
Cursor cursor = sqlDB.query(Contract.TABLE_NAME,
new String[]{Contract.Columns._ID, Contract.Columns.TASK},
null, null, null, null, null);
listAdapter = new SimpleCursorAdapter(
getActivity(),
R.layout.task_view,
cursor,
new String[]{Contract.Columns.TASK},
new int[]{R.id.taskTextView},
0
);
this.setListAdapter(listAdapter);
}
}
and this is my fragmentlayout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:id="#+id/mainLL"
android:layout_height="fill_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#android:id/list"
android:layout_weight="1"
android:layout_margin="5dp"
android:background="#color/grey"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Task"
android:id="#+id/AddButton"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:onClick="AddButtonClick"
android:layout_gravity="center_horizontal" />
</LinearLayout>
taskview
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/taskTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="20dp"
android:textColor="#color/black"
android:typeface="sans"
android:layout_toLeftOf="#+id/doneButton"
android:layout_alignBottom="#+id/doneButton"
android:gravity="center_vertical"
android:textStyle="bold"
android:layout_alignTop="#+id/doneButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Done"
android:id="#+id/doneButton"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:onClick="DoneButtonClick"
/>
</RelativeLayout>
According to android developers official website (HERE)
ListActivity has a default layout that consists of a single, full-screen list in the center of the screen. However, if you desire, you can customize the screen layout by setting your own view layout with setContentView() in onCreate(). To do this, your own view MUST contain a ListView object with the id "#android:id/list" (or list if it's in code)
for example:
<?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:paddingLeft="8dp"
android:paddingRight="8dp">
<ListView android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00FF00"
android:layout_weight="1"
android:drawSelectorOnTop="false"/>
<TextView android:id="#android:id/empty"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF0000"
android:text="No data"/>
</LinearLayout>
So either add a listview to your list activity xml or if you don't need a list view in your activity then simply use FragmentActivity to hold fragments.There is no point in using ListActivity unless it holds a ListView.
Your class is extending to a ListActivity which requires the ListView element in the xml. Your purpose be best served by extending your MainActivity class to Activity and fragments (if any) to Fragments class....
Add an list view to your xml with id android.R.id.list
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
add this xml to your layout
use Activity or FragmentActivity instead of ListActivity
if you want to use ListActivity see here once. you can use ListActivity without setting content view (setContentView()). you can directly setAdapter. or else use your own layout having one ListView with id as "#android:id/list"
EDIT :
public void onClick(View arg0) {
TextView taskTextView = (TextView) view.findViewById(R.id.taskTextView);//directly use 'view' if 'R.id.taskTextView'it present in 'view'
String task = taskTextView.getText().toString();
String sql = String.format("DELETE FROM %s WHERE %s = '%s'",
Contract.TABLE_NAME,
Contract.Columns.TASK,
task);
helper = new DBHelper(getActivity());
SQLiteDatabase sqlDB = helper.getWritableDatabase();
sqlDB.execSQL(sql);
update();
}
So i have this application, and i want to remove the logo when i run it on smaller devices sine its pressing the rest of the ui and making things look strange. It is the first application im making, so not sure how to get this done.
Here is my code for the main_activity:
package no.flammbaert.flammbaert;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.Button;
public class MainActivity extends Activity implements View.OnClickListener{
ImageButton btn_settings;
ImageButton btn_voksen;
ImageButton btn_barn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Init();
}
#Override
public void onClick(View v) {
if(v.getId() == btn_voksen.getId()){
Intent i = new Intent(MainActivity.this, VoksenActivity.class);
startActivity(i);
}
if(v.getId() == btn_settings.getId()){
Intent i = new Intent(MainActivity.this, Preferences.class);
startActivity(i);
}
if(v.getId() == btn_barn.getId()){
Intent i = new Intent(MainActivity.this, BarnActivity.class);
startActivity(i);
}
}
public void Init(){
btn_settings = (ImageButton)findViewById(R.id.btn_settings);
btn_voksen = (ImageButton) findViewById(R.id.btn_voksen);
btn_barn = (ImageButton) findViewById(R.id.btn_barn);
btn_settings.setOnClickListener(this);
btn_voksen.setOnClickListener(this);
btn_barn.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
Intent i = new Intent(MainActivity.this, Preferences.class);
startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
}
And here is the xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:background="#drawable/bg_blue_sky">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/relativeLayout"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_above="#+id/btn_settings">
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_barn"
android:background="#drawable/knapp_1"
android:layout_below="#+id/imageView"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_marginBottom="10dp" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btn_voksen"
android:background="#drawable/knapp_2"
android:layout_below="#+id/btn_barn"
android:layout_alignLeft="#+id/btn_barn"
android:layout_alignStart="#+id/btn_barn"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:background="#drawable/logo_flammbaert"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:scaleType="fitCenter"
android:adjustViewBounds="true"/>
</RelativeLayout>
<ImageButton
android:id="#+id/btn_settings"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/gear"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="10dp"
android:scaleType="fitXY"/>
</RelativeLayout>
Thanks for help.
I think you can check this way weather the app is running in a small or large screen using the below code snippet.
Configuration config = getResources().getConfiguration();
if((config.screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) ==
Configuration.SCREENLAYOUT_SIZE_SMALL)
{
//small screen
// Here you can remove/invisible the image view by using
imageView.setVisible(View.GONE);
}
This can be a aproaching to what you need:
First obtain the size of the screen take a look to this post --> Get screen dimensions in pixels
Once you get the size, you have tos et your "small screen size", and make the Imageview "dissapear.
imageview = (ImageView)findViewByID(R.id.imageView)
imageview.setVisivility(View.GONE);
Take care because there are 2 ways to make "dissapear" a view:
View.GONE This view is invisible, and it doesn't take any space for
layout purposes. View.INVISIBLE This view is invisible, but it still
takes up space for layout purposes.
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
String screenSize = dm.widthPixels
+ " "
+ dm.heightPixels;
Now if you get the smaller device resolution simply use
setVisivility(View.GONE);
But I suggest to use
Supporting Different Screen Sizes
The youtube videos i have watched and learned are at links below :-
Title is How to make an android app NO PROGRAMMING SKILLS NEEDED pt 1,2,3
1.http://www.youtube.com/watch?v=Be-YnLcPEdA , http://www.youtube.com/watch?v=Rt0wX3I1Wrg , http://www.youtube.com/watch?v=mkhRCWfTD4A.
I am a year 3 diploma student.i don't have any prior knowledge in programming and app creation.I need to develop app for my final year project.Someone please help me.I have downloaded android sdk bundle and tried to follow all as the youtube video done.
i have 3 error messages shown as below.:-
syntax error on token"(";expected.MainActivity.java .line28.type:java problem
syntax error on token")";expected.MainActivity.java .line28.type:java problem
Void is an invalid type for the variableCalculate.MainActivity.java.line28.type:java problem
Codes for main activity.java as below:-
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.widget.EditText;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
} {
public void Calculate( View v) {
EditText num1text=(EditText)findViewById(R.id.num1text);
EditText num2text=(EditText)findViewById(R.id.num2text);
Integer num1=Integer.parseInt(num1text.getText().toString()) ,num2=Integer.parseInt(num2text.getText().toString());
Integer ans=num1+num2;
TextView answer =(TextView)findViewById(R.id.answertxt);
answer.setText("answer :"+ans.toString());
}
}
}
#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;
}
}
}
Codes for Fragment main.xml are as below:-
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:orientation="vertical" >
<TextView
android:id="#+id/num1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/num1" />
<EditText
android:id="#+id/num1text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal" />
<TextView
android:id="#+id/num2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/num2" />
<EditText
android:id="#+id/num2text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal" />
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/calc"
android:onClick="Calculate" />
<TextView
android:id="#+id/answertxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/ans" />
</LinearLayout>
codes for activity_main.xml as below:-
<FrameLayout 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.test.MainActivity"
tools:ignore="MergeRootFrame" />
I need to learn how to make app because i needed to do for my project.In The real project the smartphone Android KITKAT should able to use Bluetooth Low Energy(BLE) from RFduino and Receive data from advertisement feature in BLE from RFduino and send Data back to RFduino to do some task.My Email address is yokesmohan#gmail.com,s10135557#connect.np.edu.sg.Someone please help me.
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
} {
In the line above, there is an extra open curly brace ({). Try removing it.
I'm having some issues with my school project. I can't get the text from the textbox. I searched for a solution but nothing found.. I'll be grateful if somebody help me :)
So here is my Java code:
package com.src.vicnote;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Context;
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.os.Build;
public class NewNoteActivity extends ActionBarActivity {
Button saveButton;
EditText textData;
Context context;
String text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_note);
saveButton = (Button) this.findViewById(R.id.buttonSave);
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textData = (EditText) findViewById(R.id.editText);
text = textData.getText().toString();
//text = "this is sparta!";
Log.d("ADebugTag", "string: \"" + text + "\" end of note text");
new SaveClass(text/*, context.getApplicationContext()*/);
}
});
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.new_note, 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_new_note,
container, false);
return rootView;
}
}
}
And my 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.src.vicnote.NewNoteActivity"
tools:ignore="MergeRootFrame" >
<Button
android:id="#+id/buttonSave"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="Save" />
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/buttonSave"
android:ems="10"
android:gravity="top"
android:inputType="textMultiLine" >
<requestFocus />
</EditText>
</RelativeLayout>
Also I want to ask you what will happen if the text is cyrillic? Will be there any problem?
Can't really tell what your error is without a logCat.
but one thing that might fix your problem is replacing
textData = (EditText) findViewById(R.id.editText);
text = textData.getText().toString();
with
textData = (EditText)getActivity().findViewById(R.id.editText);
text = textData.getText().toString();
// Toast for debugging purposes
Toast.makeText(getActivity(),text,0).show();
When using Fragments you should really read about getView() & getActivity().
Update
where in the xml have you set the text?
you need to set your text to something before you actually call the getText() command.
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/buttonSave"
android:ems="10"
android:gravity="top"
----- add this line ------
android:text="whatever you want"
--------------------------
android:inputType="textMultiLine" >
Good Luck
Adding a getActivity() did the trick before accessing the editText.
For example:
EditText addressText = (EditText) getActivity().findViewById(R.id.location);
getEditableText return an editable object, and you can't edit the object like that, so it is null.
simply use "getText" instead.
I don't know about Cyrillic, but it shouldn't cause any problems.