I have been tried to build my first Android Application. Every time I open the application in the emulator, I just get a message that says test has stopped working. It must be something simple. Hope you can help me.
04-06 15:43:47.806: W/dalvikvm(4275): threadid=1: thread exiting with
uncaught exception (group=0xa614d908)
04-06 15:43:47.826: E/AndroidRuntime(4275): FATAL EXCEPTION: main
04-06 15:43:47.826: E/AndroidRuntime(4275):
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.test/com.test.MainActivity}:
java.lang.NullPointerException
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.ActivityThread.access$600(ActivityThread.java:141)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.os.Handler.dispatchMessage(Handler.java:99)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.os.Looper.loop(Looper.java:137)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.ActivityThread.main(ActivityThread.java:5041)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
java.lang.reflect.Method.invokeNative(Native Method)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
java.lang.reflect.Method.invoke(Method.java:511)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
dalvik.system.NativeStart.main(Native Method)
04-06 15:43:47.826: E/AndroidRuntime(4275): Caused by:
java.lang.NullPointerException
04-06 15:43:47.826: E/AndroidRuntime(4275): at
com.test.MainActivity.onCreate(MainActivity.java:30)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.Activity.performCreate(Activity.java:5104)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
04-06 15:43:47.826: E/AndroidRuntime(4275): ... 11 more
Above is the log file
public class Main extends ActionBarActivity {
int counter ;
Button add, sub ;
TextView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0;
add = (Button) findViewById (R.id.bAdd);
sub = (Button) findViewById (R.id.bsub);
display = (TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Your total is " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter --;
display.setText("Your total is " + counter);
}
});
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;
}
}
}
Above is the Main class
<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.test.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/tvDisplay"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignLeft="#+id/bsub"
android:layout_alignParentBottom="true"
android:layout_below="#+id/bsub"
android:gravity="center"
android:text="Your total is 0"
android:textSize="45dp" />
<Button
android:id="#+id/badd"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="16dp"
android:layout_marginTop="78dp"
android:gravity="center"
android:text="Add one"
android:textSize="20dp" />
<Button
android:id="#+id/bsub"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/badd"
android:layout_centerHorizontal="true"
android:gravity="center"
android:text="Subtract one"
android:textSize="20dp" />
</RelativeLayout>
Above is the fragment_main.xml
<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.Hello.firstapp.Main"
tools:ignore="MergeRootFrame" />
ABove is the activity_main.xml
Instead of onCreate() move all ur initialization into onCreateView() as those buttons and textview is in ur fragment_main.xml thats why u got NPE as those buttons and textview is not the part of activity_main.xml.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
counter = 0;
add = (Button) rootView.findViewById (R.id.bAdd);
sub = (Button) rootView.findViewById (R.id.bsub);
display = (TextView) rootView.findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Your total is " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter --;
display.setText("Your total is " + counter);
}
});
return rootView;
}
I see your issue. activity_main.xml contains a frame layout, in which your fragment_main.xml is inflated. The thing is that, both add and sub are null, as you're looking for them in the wrong layout. Thus, call the FragmentTransaction first and move all your button code to the onCreateView of the PlaceHolderFragment and your issue should be fixed. I have provided the fixed code, all you have to do is copy it and remove the button code from onCreate (...)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
counter = 0;
add = (Button) rootView.findViewById (R.id.bAdd);
sub = (Button) rootView.findViewById (R.id.bsub);
display = (TextView) rootView.findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Your total is " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter --;
display.setText("Your total is " + counter);
}
});
return rootView;
}
Most likely
add = (Button) findViewById (R.id.bAdd);
returns null, because the element is not defined on your activity_main view.
Related
i am new in android and i was trying to make my app works in all phones
it works in 23 API and don't work in 19 API kitkat it crashes each time i open the application
Is there a way to fix this problem ?
and could you tell me what was my problem and explain it to me,
public class MainActivity extends AppCompatActivity {
private Button ButtonStart,ButtonReset ;
private TextView Number ;
private CountDownTimer myTimer ;
private MediaPlayer TimePassesSound;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButtonStart = (Button)findViewById (R.id.button); //initialize view
Number = (TextView)findViewById (R.id.textView); //initialize view
ButtonReset = (Button)findViewById (R.id.button2);
MediaPlayer TimePassesSound;
TimePassesSound = new MediaPlayer();
TimePassesSound = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
addListerOnButton (); //call method of the view
addListerOnButton2 (); //call method of the view
}
public void addListerOnButton () {
ButtonStart.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if (ButtonStart.getText ().toString () != "Stop") {
int StartTime = Integer.parseInt (Number.getText ().toString ());
myTimer = new CountDownTimer (StartTime*1000, 1000) {
public void onTick(long millisUntilFinished) {
ButtonStart.setText ("Stop");
Number.setText (""+millisUntilFinished / 1000);
}
public void onFinish() {
Number.setText("60");
ButtonStart.setText ("Start");
TimePassesSound.setLooping(false);
TimePassesSound.start();
}
}.start();
} else {
ButtonStart.setText ("Start");
myTimer.cancel ();
}
}
}
);
}
public void addListerOnButton2 () {
ButtonReset.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if ("Start".equals (ButtonStart.getText ().toString())) {
Number.setText ("60");
myTimer.cancel ();
}else{
Toast.makeText (MainActivity.this,"You must stop the countdown first",Toast.LENGTH_LONG).show();
}
}
}
);
}
}
public void addListerOnButton2 () {
ButtonReset.setOnClickListener (
new View.OnClickListener () {
public void onClick(View v) {
if ("Start".equals (ButtonStart.getText ().toString())) {
Number.setText ("60");
myTimer.cancel ();
}else{
Toast.makeText (MainActivity.this,"You must stop the countdown first",Toast.LENGTH_LONG).show();
}
}
}
);
}
}
-- Error messages
Process: com.aabdelrahman730yahoo.mydesign, PID: 3627
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.aabdelrahman730yahoo.mydesign/com.aabdelrahman730yahoo.mydesign.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.aabdelrahman730yahoo.mydesign.MainActivity.addListerOnButton(MainActivity.java:51)
at com.aabdelrahman730yahoo.mydesign.MainActivity.onCreate(MainActivity.java:43)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Main Activity :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_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.aabdelrahman730yahoo.mydesign.MainActivity"
android:touchscreenBlocksFocus="false"
android:background="#34416a">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset"
android:id="#+id/button2"
android:layout_above="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="60"
android:id="#+id/textView"
android:singleLine="true"
android:textSize="80dp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
That's was my full problem i hope someone could help me with
You are calling the method of the view without initializing it.
You need to initialize the view first and then call the method
ButtonStart = (Button)findViewById (R.id.button); //initialize view
Number = (TextView)findViewById (R.id.textView); //initialize view
addListerOnButton (); //call method of the view
addListerOnButton2 (); //call method of the view
Check this,
As #Rod_ mentioned and from error log, it clearly states that view is not initialized.
java.lang.NullPointerException
at
com.aabdelrahman730yahoo.mydesign.MainActivity.addListerOnButton(MainActivity.java:51)
at
com.aabdelrahman730yahoo.mydesign.MainActivity.onCreate(MainActivity.java:43)
Make sure following buttons were initialized in your java code.
ButtonStart and ButtonReset -- Buttonreset is not initialized here it seems.
Change your code like below.
under oncreate
ButtonStart = (Button)findViewById (R.id.button);
ButtonReset = (Button)findViewById (R.id.button_); --> You missed it ..
Number = (TextView)findViewById (R.id.textView);
addListerOnButton ();
addListerOnButton2 ();
Hope it seems clear..!!
UPDATE:
You may not initialized the media player.
The problem may be also due to usage of media player. Kindly check the code below.
MediaPlayer mediaPlayer;
mediaPlayer = new MediaPlayer();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
in your case
MediaPlayer TimePassesSound;
TimePassesSound = new MediaPlayer();
TimePassesSound = MediaPlayer.create(getApplicationContext(), R.raw.time_passing);
Add the above lines befor calling the functions.
The problem arise when I use code for Button , I am referring to The new Boston tutorials.
I am doing exactly what is told but getting error in logcat.
package com.example.myfirstapp;
import android.support.v7.app.ActionBarActivity;
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.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
int counter=0;
TextView display;
Button add;
Button sub;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add=(Button) findViewById(R.id.bAdd);
sub=(Button) findViewById(R.id.bSub);
display=(TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
counter++;
display.setText("Your Total is " +counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
counter--;
display.setText("Your Total is " +counter);
}
});
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;
}
}
}
This is my manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myfirstapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Logcat file shows these errors
: FATAL EXCEPTION: main
Process: com.example.myfirstapp, PID: 1873
E/AndroidRuntime(1873): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.myfirstapp/com.example.myfirstapp.MainActivity}: java.lang.NullPointerException
E/AndroidRuntime(1873): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
E/AndroidRuntime(1873):at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
E/AndroidRuntime(1873):at android.app.ActivityThread.access$800(ActivityThread.java:135)
E/AndroidRuntime(1873): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
E/AndroidRuntime(1873): at android.os.Handler.dispatchMessage(Handler.java:102)
E/AndroidRuntime(1873): at android.os.Looper.loop(Looper.java:136)
E/AndroidRuntime(1873): at android.app.ActivityThread.main(ActivityThread.java:5017)
E/AndroidRuntime(1873): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1873): at java.lang.reflect.Method.invoke(Method.java:515)
E/AndroidRuntime(1873): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
E/AndroidRuntime(1873): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
E/AndroidRuntime(1873): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(1873): Caused by: java.lang.NullPointerException
E/AndroidRuntime(1873): at android.view.ViewConfiguration.get(ViewConfiguration.java:325)
E/AndroidRuntime(1873): at android.view.View.<init>(View.java:3448)
E/AndroidRuntime(1873): at android.view.View.<init>(View.java:3505)
E/AndroidRuntime(1873): at android.widget.TextView.<init>(TextView.java:623)
E/AndroidRuntime(1873): at android.widget.Button.<init>(Button.java:107)
E/AndroidRuntime(1873): at android.widget.Button.<init>(Button.java:103)
E/AndroidRuntime(1873): at android.widget.Button.<init>(Button.java:99)
E/AndroidRuntime(1873): at com.example.myfirstapp.MainActivity.<init>(MainActivity.java:18)
E/AndroidRuntime(1873): at java.lang.Class.newInstanceImpl(Native Method)
E/AndroidRuntime(1873): at java.lang.Class.newInstance(Class.java:1208)
E/AndroidRuntime(1873): at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
E/AndroidRuntime(1873): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
E/AndroidRuntime(1873): ... 11 more
: I/Process(1873): Sending signal. PID: 1873 SIG: 9
This is layout xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.myfirstapp.MainActivity$PlaceholderFragment" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/hello_world"
android:textSize="45sp"
android:layout_gravity="center"
android:gravity="center"
android:id="#+id/tvDisplay"
/>
<Button
android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="#string/add_button"
android:gravity="center"
android:layout_gravity="center"
android:id="#+id/bAdd"
/>
<Button
android:id="#+id/bSub"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="#string/sub_button" />
</LinearLayout>
Please help me and please do not downvote me as I am very new and learning.
The fragment is holding the layout. You have to get the reference of buttons and textview from inflated view in onCreateView()
public static class PlaceholderFragment extends Fragment {
int counter=0;
TextView display;
Button add;
Button sub;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
add = (Button) rootView.findViewById(R.id.bAdd);
sub = (Button) rootView.findViewById(R.id.bSub);
display = (TextView) rootView.findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
counter++;
display.setText("Your Total is " +counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
counter--;
display.setText("Your Total is " +counter);
}
});
return rootView;
}
}
You are initializing Button and TextView before fragment's view is created.
Move Button, TextView initialization and callback register code before return rootView statement or override onViewCreated(View view, Bundle savedInstanceState) function of PlaceholderFragment and put code inside that method.
I am currently trying to get the basic My First App tutorial of Android (created by google) to work, but I'm having some issues. Currently how the app is made no errors show up in Eclipse, but when I run the app and click the Send button, the app crashes displaying Unfortunately, My First App has stopped.
Looking in the Log cat for the error it states that
java.lang.IllegalStateException: Could not find a method sendMessage(View)
in the activity class com.example.myfirstapp.MainActivity for onClick handler
on view class android.widget.Button.
sendMessage does exist in the MainActivity class, but it is a nested class inside a function PlaceholderFragment. Originally I thought that this was an indexing error so I tried calling sendMessage like a nested class android:onClick="PlaceholderFragment.sendMessage" with no success. I have included the fragment_main and MainActivity class as well as my full logcat error. Thanks for any help.
MainActivity:
package com.example.myfirstapp;
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.EditText;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#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();
}
}
#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;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(getActivity(), DisplayMessageActivity.class);
EditText editText = (EditText)getActivity(). findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
}
Fragment Main:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage" />
</LinearLayout>
LogCat:
04-25 12:04:07.220: D/(1274): HostConnection::get() New Host Connection established 0xb8e4f238, tid 1274
04-25 12:04:07.330: W/EGL_emulation(1274): eglSurfaceAttrib not implemented
04-25 12:04:07.340: D/OpenGLRenderer(1274): Enabling debug mode 0
04-25 12:04:10.620: D/AndroidRuntime(1274): Shutting down VM
04-25 12:04:10.620: W/dalvikvm(1274): threadid=1: thread exiting with uncaught exception (group=0xb2a6bba8)
04-25 12:04:10.750: E/AndroidRuntime(1274): FATAL EXCEPTION: main
04-25 12:04:10.750: E/AndroidRuntime(1274): Process: com.example.myfirstapp, PID: 1274
04-25 12:04:10.750: E/AndroidRuntime(1274): java.lang.IllegalStateException: Could not find a method sendMessage(View) in the activity class com.example.myfirstapp.MainActivity for onClick handler on view class android.widget.Button
04-25 12:04:10.750: E/AndroidRuntime(1274): at android.view.View$1.onClick(View.java:3810)
04-25 12:04:10.750: E/AndroidRuntime(1274): at android.view.View.performClick(View.java:4438)
04-25 12:04:10.750: E/AndroidRuntime(1274): at android.view.View$PerformClick.run(View.java:18422)
04-25 12:04:10.750: E/AndroidRuntime(1274): at android.os.Handler.handleCallback(Handler.java:733)
04-25 12:04:10.750: E/AndroidRuntime(1274): at android.os.Handler.dispatchMessage(Handler.java:95)
04-25 12:04:10.750: E/AndroidRuntime(1274): at android.os.Looper.loop(Looper.java:136)
04-25 12:04:10.750: E/AndroidRuntime(1274): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-25 12:04:10.750: E/AndroidRuntime(1274): at java.lang.reflect.Method.invokeNative(Native Method)
04-25 12:04:10.750: E/AndroidRuntime(1274): at java.lang.reflect.Method.invoke(Method.java:515)
04-25 12:04:10.750: E/AndroidRuntime(1274): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-25 12:04:10.750: E/AndroidRuntime(1274): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-25 12:04:10.750: E/AndroidRuntime(1274): at dalvik.system.NativeStart.main(Native Method)
04-25 12:04:10.750: E/AndroidRuntime(1274): Caused by: java.lang.NoSuchMethodException: sendMessage [class android.view.View]
04-25 12:04:10.750: E/AndroidRuntime(1274): at java.lang.Class.getConstructorOrMethod(Class.java:472)
04-25 12:04:10.750: E/AndroidRuntime(1274): at java.lang.Class.getMethod(Class.java:857)
04-25 12:04:10.750: E/AndroidRuntime(1274): at android.view.View$1.onClick(View.java:3803)
04-25 12:04:10.750: E/AndroidRuntime(1274): ... 11 more
04-25 12:04:12.720: I/Process(1274): Sending signal. PID: 1274 SIG: 9
It looks like your problem is that the sendMessage function should be included in your MainActivity instead of nested in your fragment.
The debug line:
java.lang.IllegalStateException: Could not find a method sendMessage(View) in the activity class com.example.myfirstapp.MainActivity for onClick handler on view class android.widget.Button
shows that the application is looking in your MainActivity class for this method.
place sendMessage(View view) method inside MainActivity class instead of PlaceholderFragment class
Handling clicklistener from xml is not always a good idea. Set a clicklistener in the fragment for the button and call sendMessage method from onClick method of clicklistener.
First set a ID for your button (Example : sendButton).
Then,
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);
Button b = (Button) rootView.findViewByID(R.id.sendButton);
//Here set the clickListener and call sendMessage method
return rootView;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(getActivity(), DisplayMessageActivity.class);
EditText editText = (EditText)getActivity(). findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
Or implement View.OnClickListener in the fragment then have a case statement like:
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.sendButton:
sendMessage();
break;
default:
Log.i(TAG, "Unknown: " + view.getId());
break;
}
}
Do it programmatically:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button b = (Button) rootView.findViewById(R.id.my_button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// handle click here
}
});
return rootView;
}
and insert this into Button section in your main activity layout:
android:id="#+id/my_button"
android:onClick="sendMessage"
button onClick attribute search the corresponding method in the Activity. but you define that method in the Fragment that's why you get the exception
method could not find exception.
Android Recommended way to do handle the onClick for button inside the fragment is
First Assign id to Button
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
/>
</LinearLayout>
your Fragment then register the button with onClick listener
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment implements OnItemClickListener{
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button b = (Button) rootView.findViewById(R.id.button1);
b.setOnClickListener(this);
return rootView;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(getActivity(), DisplayMessageActivity.class);
EditText editText = (EditText)getActivity(). findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
public void onClick(View view)
{
sendMessage(view);
}
}
I have just started writing my first piece of code in an android app, however when I run it with the following section uncommented it crashes (anything else I tell you would be a useless guess):
public void onButton1Click(View v){
if(v.getId() == R.id.button1){
StringBuilder str = new StringBuilder("");
if (pepBox.isChecked()) {
str.append("Pepperoni"+" ");
}
if (cheeseBox.isChecked()) {
str.append("Extra Cheese");
}
if (str.length() == 0) {
str.append("Plain");
}
textView.setText(str);
}
}
With the following error log:
04-07 17:45:30.897: E/AndroidRuntime(15210): FATAL EXCEPTION: main
04-07 17:45:30.897: E/AndroidRuntime(15210): Process: com.ollieapps.helloworld, PID: 15210
04-07 17:45:30.897: E/AndroidRuntime(15210): java.lang.IllegalStateException: Could not execute method of the activity
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View$1.onClick(View.java:3823)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View.performClick(View.java:4438)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View$PerformClick.run(View.java:18422)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.os.Handler.handleCallback(Handler.java:733)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.os.Handler.dispatchMessage(Handler.java:95)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.os.Looper.loop(Looper.java:136)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-07 17:45:30.897: E/AndroidRuntime(15210): at java.lang.reflect.Method.invoke(Native Method)
04-07 17:45:30.897: E/AndroidRuntime(15210): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-07 17:45:30.897: E/AndroidRuntime(15210): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-07 17:45:30.897: E/AndroidRuntime(15210): Caused by: java.lang.reflect.InvocationTargetException
04-07 17:45:30.897: E/AndroidRuntime(15210): at java.lang.reflect.Method.invoke(Native Method)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View$1.onClick(View.java:3818)
04-07 17:45:30.897: E/AndroidRuntime(15210): ... 9 more
04-07 17:45:30.897: E/AndroidRuntime(15210): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.CheckBox.isChecked()' on a null object reference
04-07 17:45:30.897: E/AndroidRuntime(15210): at com.ollieapps.helloworld.MainActivity.onButton1Click(MainActivity.java:59)
04-07 17:45:30.897: E/AndroidRuntime(15210): ... 11 more
I'm sorry if I have included to much or too little, this is my first question, also I have already searched for 3 hours.
Full Code:
package com.ollieapps.helloworld;
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.CheckBox;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView textView; CheckBox pepBox, cheeseBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pepBox = (CheckBox) findViewById(R.id.checkBox1);
cheeseBox = (CheckBox) findViewById(R.id.checkBox2);
textView = (TextView) findViewById(R.id.textView1);
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);
}
public void onButton1Click(View v){
if(v.getId() == R.id.button1){
StringBuilder str = new StringBuilder("");
if (pepBox.isChecked()) {
str.append("Pepperoni"+" ");
}
if (cheeseBox.isChecked()) {
str.append("Extra Cheese");
}
if (str.length() == 0) {
str.append("Plain");
}
textView.setText(str);
}
}
/**
* 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;
}
}
}
xml:
fragment:
<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.ollieapps.helloworld.MainActivity$PlaceholderFragment" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pepperoni" />
<CheckBox
android:id="#+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ExtraCheese" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onButton1Click"
android:text="Show" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Plain" />
</LinearLayout>
</RelativeLayout>
Main:
<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.ollieapps.helloworld.MainActivity"
tools:ignore="MergeRootFrame" />
It seems you built your views inside fragment_main.xml and not activity_main.xml.
When you first create a new android project, you have these files which are automatically created and opened:
Then, when you begin, you add views (e.g: a TextView) inside fragment_main.xml file. Finally, you tried to do a basically event with this view inside your Activity, something like this:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Using layout activity_main.xml
// You try to set a simple text on the view (TextView) previously added
TextView text = (TextView) findViewById(R.id.textView1);
text.setText("Simple Text"); // And you get an error here!
/*
* You do an fragment transaction to add PlaceholderFragment Fragment
* on screen - this below snippnet is automatically created.
*/
if(savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
You cannot run your app or sometimes you have only a white screen, because the views that you tried to call/display are into the wrong layout..
Solution: Move all your stuff inside onCreateView method into the Fragment class.
As DoctororDrive said in his comment
Call views and do something in the related fragment and not the parent activity.
For example, in your case, these following lines:
pepBox = (CheckBox) findViewById(R.id.checkBox1);
cheeseBox = (CheckBox) findViewById(R.id.checkBox2);
textView = (TextView) findViewById(R.id.textView1);
might be inside your fragment because you created it in fragment_main.xml layout. Then:
// start fragment
public static class PlaceholderFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Use the layout which is displayed it's fragment_main.xml
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Find your views here!
// Don't forget to findViewById attached to the inflated view "rootView.findView..."
pepBox = (CheckBox) rootView.findViewById(R.id.checkBox1);
cheeseBox = (CheckBox) rootView.findViewById(R.id.checkBox2);
textView = (TextView) rootView.findViewById(R.id.textView1);
/*
* Do something here: click listener, set a text, check a box..
*/
return rootView;
}
/*
* Perform other methods still inside the fragment
*/
public void onButton1Click(View v){
if(v.getId() == R.id.button1){
StringBuilder str = new StringBuilder("");
if (pepBox.isChecked()) {
str.append("Pepperoni"+" ");
}
if (cheeseBox.isChecked()) {
str.append("Extra Cheese");
}
if (str.length() == 0) {
str.append("Plain");
}
textView.setText(str);
}
}
}
// end fragment
if (pepBox.isChecked()) {
This line of code is failing with a NullPointerException because pepBox was declared but it's not being initialized as it should (and is therefore null at this point in the code).
Here is its declaration line:
TextView textView; CheckBox pepBox, cheeseBox;
And here is its initialization:
pepBox = (CheckBox) findViewById(R.id.checkBox1);
The problem is that (a) this line is not be called, or (b) findViewById(R.id.checkBox1) is returning null.
If findViewByID is returning null then you probably want to refer to this question, which addresses exactly this issue. Its "related questions", down the right-hand side, should also be helpful.
I am using this library https://github.com/chrisbanes/Android-PullToRefresh for implementing a refreshable grid view and i am getting this error:
android.view.InflateException: Binary XML file line #8: Error inflating class com.handmark.pulltorefresh.library.PullToRefreshGridView
at android.view.LayoutInflater.createView(LayoutInflater.java:518)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:570)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:623)
at android.view.LayoutInflater.inflate(LayoutInflater.java:408)
at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
at com.example.retrievetweets.FragmentPhotos.onCreateView(FragmentPhotos.java:55)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:461)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1011)
at android.support.v4.view.ViewPager.populate(ViewPager.java:880)
at android.support.v4.view.ViewPager$3.run(ViewPager.java:238)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:415)
at android.view.LayoutInflater.createView(LayoutInflater.java:505)
... 24 more
Caused by: java.lang.NullPointerException
at com.handmark.pulltorefresh.library.internal.IndicatorLayout.<init>(IndicatorLayout.java:66)
at com.handmark.pulltorefresh.library.PullToRefreshAdapterViewBase.addIndicatorViews(PullToRefreshAdapterViewBase.java:355)
at com.handmark.pulltorefresh.library.PullToRefreshAdapterViewBase.updateUIForMode(PullToRefreshAdapterViewBase.java:328)
at com.handmark.pulltorefresh.library.PullToRefreshBase.init(PullToRefreshBase.java:1142)
at com.handmark.pulltorefresh.library.PullToRefreshBase.<init>(PullToRefreshBase.java:113)
at com.handmark.pulltorefresh.library.PullToRefreshAdapterViewBase.<init>(PullToRefreshAdapterViewBase.java:74)
at com.handmark.pulltorefresh.library.PullToRefreshGridView.<init>(PullToRefreshGridView.java:35)
... 27 more
Here is the xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<!-- The PullToRefreshGridView replaces a standard GridView widget. -->
<com.handmark.pulltorefresh.library.PullToRefreshGridView
xmlns:ptr="http://schemas.android.com/apk/res-auto"
android:id="#+id/pull_refresh_grid"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:numColumns="auto_fit"
android:verticalSpacing="0dp"
android:horizontalSpacing="1dp"
android:columnWidth="80dp"
android:stretchMode="columnWidth"
android:gravity="fill"
ptr:ptrMode="both"
ptr:ptrDrawable="#drawable/default_ptr_rotate"
/>
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:indeterminateOnly="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>
And here is the java code for the method onCreateView in FragmentPhotos (the line 55 is this one "ll = (RelativeLayout) inflater.inflate(R.layout.activity_grid_view,"):
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ref = "";
fa = getActivity();
ll = (RelativeLayout) inflater.inflate(R.layout.activity_grid_view,
container, false);
bar = (ProgressBar) ll.findViewById(R.id.progressBar);
mPullRefreshGridView = (PullToRefreshGridView) ll
.findViewById(R.id.pull_refresh_grid);
mGridView = mPullRefreshGridView.getRefreshableView();
// Set a listener to be invoked when the list should be refreshed.
mPullRefreshGridView
.setOnRefreshListener(new OnRefreshListener<GridView>() {
#Override
public void onRefresh(
PullToRefreshBase<GridView> refreshView) {
// TODO Auto-generated method stub
if (NetworkReceiver.mobileConnected) {
new GetDataTaskWhitoutLoading().execute();
} else {
Toast.makeText(
getActivity(),
"Ahora mismo no se pueden cargar nuevos datos."
+ " Comprueba la conexi—n a Internet.",
Toast.LENGTH_LONG).show();
mPullRefreshGridView.onRefreshComplete();
}
}
});
mGridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position,
long id) {
// Do something in response to the click
Intent intent = new Intent(fa, ImageSelected.class);
intent.putExtra("URL_image", mListItems.get(position)
.subSequence(0, mListItems.get(position).length() - 6));
startActivity(intent);
}
});
mListItems = new ArrayList<String>();
mAdapter = new FotosItemAdapter(fa, R.layout.image_group, mListItems);
mGridView.setAdapter(mAdapter);
if (NetworkReceiver.mobileConnected) {
GetDataTask.newInstance(bar).execute();
}
return ll;
}
Thank you!!
Are you importing in your classhpath on eclipse?
Pull to refhresh is a lib for android,then import like this:
project properties> android> add lib.
In my case it solved by adding this to my project.properties :
target=android-19
android.library.reference.1=../library
that library is the name of the handmark library.
hope be useful.