Well, I have this problem and I don't know why because Eclipse doesn't tells me which the error is. I'm a beginner in Java and I don't know what to do. Here's my code:
package com.example.asado;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
public class ListaActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set View to register.xml
setContentView(R.layout.listas);
addListenerOnButton();
final ListView listview = (ListView) findViewById(R.id.lista_compra);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux",
"OS/2", "Ubuntu", "Windows7", "Max OS X", "Linux", "OS/2",
"Android", "iPhone", "WindowsMobile" };
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
list.add(values[i]);
}
final StableArrayAdapter adapter = new StableArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN) #Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final String item = (String) parent.getItemAtPosition(position);
view.animate().setDuration(2000).alpha(0)
.withEndAction(new Runnable() {
#Override
public void run() {
list.remove(item);
adapter.notifyDataSetChanged();
view.setAlpha(1);
}
});
}
});
}
private class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
#Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
}
public void addListenerOnButton() {
ImageButton compra = (ImageButton) findViewById(R.id.compra);
// Listening to Login Screen link
compra.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// Cierro la ventana
// cambio de pesta�a
finish();
}
});
}
}
It's a bit messy but the error is that when this layout is about to open, I get the error "Unfortunately the application has stopped". Thanks in advance.
These are the Errors at Logcat:
07-23 16:05:06.509: E/AndroidRuntime(8794): FATAL EXCEPTION: main
07-23 16:05:06.509: E/AndroidRuntime(8794): Process: com.example.asado, PID: 8794
07-23 16:05:06.509: E/AndroidRuntime(8794): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.asado/com.example.asado.ListaActivity}: java.lang.NullPointerException
07-23 16:05:06.509: E/AndroidRuntime(8794): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
07-23 16:05:06.509: E/AndroidRuntime(8794): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
07-23 16:05:06.509: E/AndroidRuntime(8794): at android.app.ActivityThread.access$800(ActivityThread.java:139)
07-23 16:05:06.509: E/AndroidRuntime(8794): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
07-23 16:05:06.509: E/AndroidRuntime(8794): at android.os.Handler.dispatchMessage(Handler.java:102)
07-23 16:05:06.509: E/AndroidRuntime(8794): at android.os.Looper.loop(Looper.java:136)
07-23 16:05:06.509: E/AndroidRuntime(8794): at android.app.ActivityThread.main(ActivityThread.java:5102)
07-23 16:05:06.509: E/AndroidRuntime(8794): at java.lang.reflect.Method.invokeNative(Native Method)
07-23 16:05:06.509: E/AndroidRuntime(8794): at java.lang.reflect.Method.invoke(Method.java:515)
07-23 16:05:06.509: E/AndroidRuntime(8794): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-23 16:05:06.509: E/AndroidRuntime(8794): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-23 16:05:06.509: E/AndroidRuntime(8794): at dalvik.system.NativeStart.main(Native Method)
07-23 16:05:06.509: E/AndroidRuntime(8794): Caused by: java.lang.NullPointerException
07-23 16:05:06.509: E/AndroidRuntime(8794): at com.example.asado.ListaActivity.onCreate(ListaActivity.java:39)
07-23 16:05:06.509: E/AndroidRuntime(8794): at android.app.Activity.performCreate(Activity.java:5248)
07-23 16:05:06.509: E/AndroidRuntime(8794): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
07-23 16:05:06.509: E/AndroidRuntime(8794): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2173)
07-23 16:05:06.509: E/AndroidRuntime(8794): ... 11 more
Try to replace:
#Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
with this:
#Override
public long getItemId(int position) {
return position;
}
ListActivity's line 39 has nullpointer see if list is set correctly, if you look at this example List works better if its id is created #android:id/list instead of created by giving id value.
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
Related
I have this problem that whenever i click on the listView OnItemClick method it always crashes when it is trying to reach another intent down below i leave some code.
public class SelectFichas extends AppCompatActivity {
TextView tv;
ListView lv;
RecyclerView.LayoutManager mLayoutManager;
ImageButton btn1;
ArrayList<Ficha> slFichas;
List<Ficha> ftchArray;
DBHelper db;
MyAdapter aAdapt = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_ficha);
btn1 = (ImageButton) (findViewById(R.id.rg));
lv = (ListView) (findViewById(R.id.lv1));
db = new DBHelper(this);
try {
//Verificamos que la base de datos no este vacia
if (!db.isEmpty()) {
ftchArray = db.getAllFichas();
slFichas = new ArrayList<Ficha>();
for (Ficha fi : ftchArray) {
slFichas.add(fi);
}
// mAdapter = new MyAdapter(ftchArray,getApplication());
aAdapt = new MyAdapter(SelectFichas.this,0,slFichas);
View header = getLayoutInflater().inflate(R.layout.list_header, null);
lv.addHeaderView(header);
lv.setAdapter(aAdapt);
lv.setItemsCanFocus(false);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick( AdapterView<?> parent, View view, int position, long id) {
Ficha fi = (Ficha) aAdapt.getItem(position-1);
String sel = fi.getPreg();
String[] opc = {"Actualizar", "Borrar", "Adivinar", "Atras"};
Toast.makeText(getApplicationContext(), "Usted selecciono " +sel, Toast.LENGTH_SHORT).show();
final Intent intent = new Intent(SelectFichas.this,UpdFicha.class);
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
if (intent.resolveActivity(getPackageManager()) != null){
startActivity(intent);
}
}
}, 2000);
I also used a custom ArrayAdapter for my ListView is that influencing, in case i will leave some code about the adapter below.
public class MyAdapter extends ArrayAdapter<Ficha> {
private Context context;
private ArrayList<Ficha> ficha;
public MyAdapter(Context context, int resource, ArrayList<Ficha> objects) {
super(context, resource, objects);
this.context = context;
this.ficha = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
Ficha fi = ficha.get(position);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.list_items, parent,false);
RelativeLayout rv = (RelativeLayout)(view.findViewById(R.id.relativeLayout));
TextView id = (TextView)view.findViewById(R.id.id_view);
TextView preg = (TextView)view.findViewById(R.id.preg_view);
TextView ans = (TextView) view.findViewById(R.id.answer_view);
id.setText(String.valueOf(fi.getId()));
preg.setText(fi.getPreg());
ans.setText(fi.getRes());
return view;
}
}
Here is my Logcat EDITED
2-05 11:52:06.886 5997-5997/com.giamp.fichas W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x9ccbcb20)
12-05 11:52:06.886 5997-5997/com.giamp.fichas E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.giamp.fichas, PID: 5997
java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:386)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:193)
at android.widget.Spinner.onMeasure(Spinner.java:482)
at android.support.v7.widget.AppCompatSpinner.onMeasure(AppCompatSpinner.java:416)
at android.view.View.measure(View.java:16497)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:389)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
at android.view.View.measure(View.java:16497)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
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.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.TextView
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:379)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:193)
at android.widget.Spinner.onMeasure(Spinner.java:482)
at android.support.v7.widget.AppCompatSpinner.onMeasure(AppCompatSpinner.java:416)
at android.view.View.measure(View.java:16497)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.support.v7.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:389)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:16497)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
at android.view.View.measure(View.java:16497)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
at android.view.Choreographer.doCallbacks(Choreographer.java:574)
at android.view.Choreographer.doFrame(Choreographer.java:544)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
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)
AdapterView<?> parent is not an Adapter, but it is a ViewGroup.
change
ArrayAdapter<Ficha> aAdapt = new MyAdapter(SelectFichas.this, 0, slFichas);
to
final MyAdapter aAdapt = new MyAdapter(SelectFichas.this, 0, slFichas);
and
Ficha fi = (Ficha) parent.getItemAtPosition(position);
to
Ficha fi = (Ficha) aAdapt.getItem(position);
When I call .notifyDataSetChanged() in my constructor after I set my ArrayList my app still crashes, the same as when I call it before I call .setAdapter, it's been bothering me for hours, would love any kind of help, thanks!
public class CustomSwipeAdapter extends PagerAdapter {
private ArrayList<String> image_resources = new ArrayList<>();
private Context mContext;
private LayoutInflater mLayoutInflater;
private ImageLoader mImageLoader;
public CustomSwipeAdapter(Context context, ArrayList<String> images){
this.mContext = context;
this.image_resources = images;
}
#Override
public int getCount() {
return image_resources.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == (LinearLayout)object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
mLayoutInflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
View item_view = mLayoutInflater.inflate(R.layout.swipe_layout, container, false);
final ImageView imageView = (ImageView) item_view.findViewById(R.id.imageView);
if (image_resources.get(position) != null || !image_resources.get(position).isEmpty()) {
mImageLoader.get(image_resources.get(position), new ImageLoader.ImageListener() {
#Override
public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
imageView.setImageBitmap(response.getBitmap());
}
#Override
public void onErrorResponse(VolleyError error) {
imageView.setBackgroundColor(Color.CYAN);
}
});
}
container.addView(item_view);
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout) object);
super.destroyItem(container, position, object);
}
}
Where I set my Adapter (in my Activity's onCreate()), it's most basic activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_page);
mViewPager = (ViewPager) findViewById(R.id.view_pager);
mVolleySingleton = VolleySingleton.getInstance();
mRequestQueue = mVolleySingleton.getRequestQueue();
sendAPIRequest();
//after you get the images
mCustomSwipeAdapter = new CustomSwipeAdapter(this, images);
mViewPager.setAdapter(mCustomSwipeAdapter);
}
Stack Trace:
java.lang.IllegalStateException: The application's PagerAdapter changed the adapter's contents without calling PagerAdapter#notifyDataSetChanged! Expected adapter item count: 0, found: 4 Pager id: sobmad.com.gamingreminder:id/view_pager Pager class: class android.support.v4.view.ViewPager Problematic adapter: class sobmad.com.gamingreminder.GamePage.CustomSwipeAdapter
at android.support.v4.view.ViewPager.populate(ViewPager.java:967)
at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
at android.view.View.measure(View.java:15848)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:728)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:477)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.support.v7.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:453)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
at android.view.View.measure(View.java:15848)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5012)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2189)
at android.view.View.measure(View.java:15848)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1905)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1104)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1284)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
at android.view.Choreographer.doCallbacks(Choreographer.java:562)
at android.view.Choreographer.doFrame(Choreographer.java:532)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
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:5103)
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:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
mCustomSwipeAdapter = new CustomSwipeAdapter(this, images);
mViewPager.setAdapter(mCustomSwipeAdapter);
mCustomSwipeAdapter.notifyDataSetChange() //Add this line in your activity
I created a button and assigned it 1 by doing
remove.setId(0 + count);
Then I tried to put that button in my onCreate bundle to use it
Button remove = (Button)findViewById(1);
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
When I create the button remove in my oncreate it runs but as soon as I add my onclick listener I dont get any errors but when I run it it force closes
Log
12-12 13:42:06.172: D/AndroidRuntime(19502): Shutting down VM
12-12 13:42:06.172: W/dalvikvm(19502): threadid=1: thread exiting with uncaught exception (group=0x416bbd40)
12-12 13:42:06.178: E/AndroidRuntime(19502): FATAL EXCEPTION: main
12-12 13:42:06.178: E/AndroidRuntime(19502): Process: com.th3ramr0d.armytrooptotask, PID: 19502
12-12 13:42:06.178: E/AndroidRuntime(19502): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.th3ramr0d.armytrooptotask/com.th3ramr0d.armytrooptotask.MainActivity}: java.lang.NullPointerException
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2269)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.access$800(ActivityThread.java:139)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.os.Handler.dispatchMessage(Handler.java:102)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.os.Looper.loop(Looper.java:136)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.main(ActivityThread.java:5102)
12-12 13:42:06.178: E/AndroidRuntime(19502): at java.lang.reflect.Method.invokeNative(Native Method)
12-12 13:42:06.178: E/AndroidRuntime(19502): at java.lang.reflect.Method.invoke(Method.java:515)
12-12 13:42:06.178: E/AndroidRuntime(19502): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
12-12 13:42:06.178: E/AndroidRuntime(19502): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
12-12 13:42:06.178: E/AndroidRuntime(19502): at dalvik.system.NativeStart.main(Native Method)
12-12 13:42:06.178: E/AndroidRuntime(19502): Caused by: java.lang.NullPointerException
12-12 13:42:06.178: E/AndroidRuntime(19502): at com.th3ramr0d.armytrooptotask.MainActivity.onCreate(MainActivity.java:45)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.Activity.performCreate(Activity.java:5248)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
12-12 13:42:06.178: E/AndroidRuntime(19502): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2173)
12-12 13:42:06.178: E/AndroidRuntime(19502): ... 11 more
Here is my full file
package com.th3ramr0d.armytrooptotask;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
public int count = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addTroopBtn = (Button) findViewById(R.id.addTroop);
addTroopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(count <= 5)
{
inputName(v);
}
else
{
}
}
});
Button remove = (Button)findViewById(1);
remove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
public void inputName(final View v){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
//alert.setTitle("Enter Name and Rank");
alert.setMessage("Please Enter A Name");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable name = input.getText();
addTroop(name);
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
public void addTroop(Editable name){
LinearLayout mainPage = (LinearLayout) findViewById(R.id.manageTroopsMain);
if (count <= 5)
{
//CREATE NEW LINEAR LAYOUT
LinearLayout addTroopLayout = new LinearLayout(this);
//CREATE LAYOUT PARAMS FOR LAYOUT
LinearLayout.LayoutParams newLayout = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
newLayout.bottomMargin = 10;
//STYLE NEW LINEAR LAYOUT
addTroopLayout.setTag("addTroopLayout" + count);
addTroopLayout.setLayoutParams(newLayout);
addTroopLayout.setOrientation(LinearLayout.HORIZONTAL);
//CREATE NEW BUTTONS
Button newTroop = new Button(this);
Button remove = new Button(this);
Button change = new Button(this);
//CREATE LAYOUT PARAMS FOR BUTTONS
LinearLayout.LayoutParams newTroopParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 20f);
LinearLayout.LayoutParams rmvBtnParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, .5f);
LinearLayout.LayoutParams chngNameParam = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, .5f);
//STYLE NEW BUTTONS
newTroop.setText(name);
newTroop.setGravity(Gravity.LEFT|Gravity.CENTER_VERTICAL);
newTroop.setLayoutParams(newTroopParam);
remove.setId(0 + count);
remove.setText("-");
remove.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
remove.setLayoutParams(rmvBtnParam);
change.setText("...");
change.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
change.setLayoutParams(chngNameParam);
//ADD VIEWS TO NEW LAYOUT
addTroopLayout.addView(newTroop);
addTroopLayout.addView(remove);
addTroopLayout.addView(change);
//ADD NEW LAYOUT TO mainPage LAYOUT
mainPage.addView(addTroopLayout);
//Increment Counter
count++;
}
}
}
This is your problem:
Button remove = (Button)findViewById(1);
This should be something like this:
Button remove = (Button)findViewById(R.id.buttonRemove); // that should be a long int
The crash is likely happening from this line:
Button remove = (Button)findViewById(1);
You'll need to provide a valid ID for a Button within your inflated layout. A value of 1 is not meaningful.
I know this answer is probably simple but i cannot figure it out. I am modifying example code for a project and keep getting a ClassCastException when i try to launch the app. Says that ListActivityFragment cannot be cast to android.app.Activity. What im not understanding(which is probably the simple part) is why its trying to cast it onto an activity when my main is a fragmentactivity. I know the code is rough, still trying to finish it up but cant get past this.
FragmentActivity
public class MainActivity extends FragmentActivity {
private boolean isLargeScreen = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (findViewById(R.id.normal_screen_layout) != null) {
isLargeScreen = false;
ListActivityFragment listActivityFragment = new ListActivityFragment();
listActivityFragment.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.normal_screen_layout, listActivityFragment)
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addItem:
ListActivityFragment newFragment = new ListActivityFragment();
FragmentTransaction transaction = getSupportFragmentManager()
.beginTransaction();
transaction.replace(R.id.normal_screen_layout, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
}
ListActivity
public class ListActivityFragment extends ListFragment implements
OnClickListener {
private ArrayList<String> items = new ArrayList<String>();
private ListView listView;
private View outerView;
private Button deleteButton;
private ListActivityListener listener;
public interface ListActivityListener {
public void meetingAdded();
}
public ListActivityFragment() {
}
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
listener = (ListActivityListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
outerView = inflater.inflate(R.layout.list_of_meetings, container,
false);
listView = (ListView) outerView.findViewById(R.id.listView1);
deleteButton = (Button) outerView.findViewById(R.id.deleteButton);
createList();
return outerView;
}
public void createList() {
items.clear();
Iterator<Items> iterator = ItemCollection.Instance().iterator();
while (iterator.hasNext()) {
items.add(iterator.next().toString());
}
listView.setAdapter(new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, items));
}
#Override
public void onClick(DialogInterface arg0, int arg1) {
ListView listView = getListView();
for (int index = 0; index < listView.getChildCount(); index++) {
View viewGroup = listView.getChildAt(index);
CheckBox checkBox = (CheckBox) viewGroup
.findViewById(R.id.itemSelectCheckBox);
if (checkBox.isChecked()) {
TextView textView = (TextView) viewGroup
.findViewById(R.id.productTextView);
int key = (Integer) textView.getTag();
ItemCollection.Instance().delete(key);
}
}
createList();
}
#Override
public void onStart() {
super.onStart();
}
public void onListItemClick(ListView l, View v, int position, long id) {
getListView().setItemChecked(position, true);
}
}
And heres the Logcat
07-15 01:59:50.710: E/AndroidRuntime(878): FATAL EXCEPTION: main
07-15 01:59:50.710: E/AndroidRuntime(878): Process: com.example.assignment5, PID: 878
07-15 01:59:50.710: E/AndroidRuntime(878): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.assignment5/com.example.assignment5.ListActivityFragment}: java.lang.ClassCastException: com.example.assignment5.ListActivityFragment cannot be cast to android.app.Activity
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2121)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread.access$800(ActivityThread.java:135)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.os.Handler.dispatchMessage(Handler.java:102)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.os.Looper.loop(Looper.java:136)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread.main(ActivityThread.java:5017)
07-15 01:59:50.710: E/AndroidRuntime(878): at java.lang.reflect.Method.invokeNative(Native Method)
07-15 01:59:50.710: E/AndroidRuntime(878): at java.lang.reflect.Method.invoke(Method.java:515)
07-15 01:59:50.710: E/AndroidRuntime(878): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-15 01:59:50.710: E/AndroidRuntime(878): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-15 01:59:50.710: E/AndroidRuntime(878): at dalvik.system.NativeStart.main(Native Method)
07-15 01:59:50.710: E/AndroidRuntime(878): Caused by: java.lang.ClassCastException: com.example.assignment5.ListActivityFragment cannot be cast to android.app.Activity
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
07-15 01:59:50.710: E/AndroidRuntime(878): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2112)
07-15 01:59:50.710: E/AndroidRuntime(878): ... 11 more
07-15 01:59:51.160: E/NetdConnector(383): NDC Command {65 bandwidth setiquota eth0 9223372036854775807} took too long (1117ms)
Caused by: java.lang.ClassCastException:
com.example.assignment5.ListActivityFragment cannot be cast to
android.app.Activity 07-15 01:59:50.710: E/AndroidRuntime(878):
As the error says -
ListActivityFragment is not an activity. So you are trying to access it just like an activity.
Make sure you haven't declared ListActivityFragment in the manifest. In your manifest if you made an entry for the fragment then that's wrong.
Also make sure that you haven't used startActivity for the fragment. Because this is done for activity class and not for fragment class.
I've built some class named "item", here is it: (thats the whole code)
public class item {
private int id;
private String title;
private String desc;
private double lat;
private double lon;
private String pub;
private int p;
private int n;
public item(int id, String title, String desc, double lat, double lon, String pub, int p, int n) {
super();
this.id = id;
this.title = title;
this.desc = desc;
this.lat = lat;
this.lon = lon;
this.pub = pub;
this.p = p;
this.n = n;
}
Now I have to make a List<item> and add() "item"s to it, but for some reason my application crushes.
Thats the Activity:
public class MainActivity extends Activity {
List<item> markers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
item a = new item(1, "lol", "sdfs", 32.45345, 34.54353, "nir", 0, 0);
markers.add(a);
}
LOGCAT:
08-10 16:32:46.710: D/AndroidRuntime(2934): Shutting down VM
08-10 16:32:46.710: W/dalvikvm(2934): threadid=1: thread exiting with uncaught exception (group=0x41a0a930)
08-10 16:32:46.777: E/AndroidRuntime(2934): FATAL EXCEPTION: main
08-10 16:32:46.777: E/AndroidRuntime(2934): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testitems/com.example.testitems.MainActivity}: java.lang.NullPointerException
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2308)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.ActivityThread.access$600(ActivityThread.java:153)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.os.Handler.dispatchMessage(Handler.java:99)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.os.Looper.loop(Looper.java:137)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.ActivityThread.main(ActivityThread.java:5227)
08-10 16:32:46.777: E/AndroidRuntime(2934): at java.lang.reflect.Method.invokeNative(Native Method)
08-10 16:32:46.777: E/AndroidRuntime(2934): at java.lang.reflect.Method.invoke(Method.java:511)
08-10 16:32:46.777: E/AndroidRuntime(2934): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
08-10 16:32:46.777: E/AndroidRuntime(2934): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
08-10 16:32:46.777: E/AndroidRuntime(2934): at dalvik.system.NativeStart.main(Native Method)
08-10 16:32:46.777: E/AndroidRuntime(2934): Caused by: java.lang.NullPointerException
08-10 16:32:46.777: E/AndroidRuntime(2934): at com.example.testitems.MainActivity.onCreate(MainActivity.java:18)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.Activity.performCreate(Activity.java:5104)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
08-10 16:32:46.777: E/AndroidRuntime(2934): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2262)
08-10 16:32:46.777: E/AndroidRuntime(2934): ... 11 more
Appreciate your help guys!
Initialize your markers list
List<item> markers=new ArrayList<item>();
try this
public class MainActivity extends Activity {
ArrayList<item> markers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
markers = new ArrayList<item>();
item a = new item(1, "lol", "sdfs", 32.45345, 34.54353, "nir", 0, 0);
markers.add(a);
}
You have to initialize the list before you use it.
setContentView(R.layout.activity_main);
List<item> markers = new ArrayList<item>();
item a = new item(1, "lol", "sdfs", 32.45345, 34.54353, "nir", 0, 0);
markers.add(a);
Any object should be initialized before using its methods, however you seem to forgot this step before adding data in your list. Initialize markers before adding data in it.
List<item> markers=new ArrayList<item>();
In the code you have not initialize the arraylist object to remove these errors
see the following steps mention below:
First allocate memory to the Arraylist object like this
public class MainActivity extends Activity {
ArrayList markers;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
markers = new ArrayList<item>();
item a = new item(1, "lol", "sdfs", 32.45345, 34.54353, "nir", 0, 0);
markers.add(a);
}
Secondly to handle the error use the try and the catch block .
public class MainActivity extends Activity {
ArrayList markers;
#Override
protected void onCreate(Bundle savedInstanceState) {
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
markers = new ArrayList<item>();
item a = new item(1, "lol", "sdfs", 32.45345, 34.54353, "nir", 0, 0);
markers.add(a);
}
catch(Exception e)
{
//Write to android ddms logger.
or
make a Toast Message
}
}
Free the resources which has been intialize like arraylist etc.
By putting finally block after the catch Block.