I worked at school on a programm, but when I try to start it on my pc at home I get this error (I copied the project on a usb):
02-08 14:41:57.212 1672-1672/sia.school.sia14_15 E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{sia.school.sia14_15/sia.school.sia14_15.SIA_tabbedActivity}: android.content.res.Resources$NotFoundException: String array resource ID #0x7f050003
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: String array resource ID #0x7f050003
at android.content.res.Resources.getStringArray(Resources.java:450)
at sia.homag.sia14_15.SIA_tabbedActivity.onCreate(SIA_tabbedActivity.java:51)
R file:
public final class R {
public static final class anim {
public static final int abc_fade_in=0x7f040000;
public static final int abc_fade_out=0x7f040001;
public static final int abc_slide_in_bottom=0x7f040002;
public static final int abc_slide_in_top=0x7f040003;
public static final int abc_slide_out_bottom=0x7f040004;
public static final int abc_slide_out_top=0x7f040005;
}
public static final class array {
public static final int a_9083646153=0x7f050002;
public static final int agregat_xy=0x7f050000;
public static final int b_9083646153=0x7f050003; //yes, the names do have some meaning
}
/*...*/
SIA_tabbedAvtivity:
public class SIA_tabbedActivity extends ActionBarActivity
{
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
private String[] strArray;
private String scanResult; // Speichert das Ergebnis des Barcodescanns
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
/*Error -> */ strArray = getResources().getStringArray(R.array.b_9083646153);
setContentView(R.layout.activity_sia_tabbed);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
} /*...*/
It worked fine at school. I already tried to clean and rebuild the project and deleted the R file to regenerate it but nothing worked. And yes, there is a string array in a .xml with the correct name.
Related
I have created a dashboard of my app containing six buttons on it. My Project code compiles perfectly without showing any error.
When I click on any button for 1st time it also response perfectly but when i click for 2nd time at another button My App Crashes completely and it shows errors in Run tab.
I have googled many times but nothing to solve my critical statement
Seeds class(MainActivity) is here:
public class Seeds extends AppCompatActivity {
RecyclerView mRecyclerView;
List<SeedsData> mySeedsList;
SeedsData mSeedsData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_seeds);
mRecyclerView = (RecyclerView)findViewById(R.id.recyclerView2);
GridLayoutManager gridLayoutManager;
gridLayoutManager = new GridLayoutManager(Seeds.this, 1);
mRecyclerView.setLayoutManager(gridLayoutManager);
mySeedsList = new ArrayList<>();
mSeedsData = new SeedsData("Wheat","Wheat is a grass widely cultivated for its seed, a cereal grain which is a worldwide staple food. The many species of wheat together make up the genus Triticum; the most widely grown is common wheat (T. aestivum). Botanically, the wheat kernel is a type of fruit called a caryopsis.","Rs.50",R.drawable.wheat);
mySeedsList.add(mSeedsData);
mSeedsData = new SeedsData("Peanut","Peanut seeds are planted one to two inches deep, one every six inches or so apart, in rows about three feet apart. ... Thirty to forty days after emergence the plants bloom, form and enter the soil. The peanut shells and kernels develop and mature during the next 60 to 70 day period.","Rs.6000",R.drawable.peanut);
mySeedsList.add(mSeedsData);
mSeedsData = new SeedsData("Almond","The fruit of the almond is a drupe, consisting of an outer hull and a hard shell with the seed, which is not a true nut, inside. Shelling almonds refers to removing the shell to reveal the seed","Rs.700",R.drawable.almond);
mySeedsList.add(mSeedsData);
MyAdapter2 myAdapter2 = new MyAdapter2(Seeds.this,mySeedsList);
mRecyclerView.setAdapter(myAdapter2);
}
}
SeedsData class code is here:
public class SeedsData {
private String itemName;
private String itemDescription;
private String itemPrice;
private int itemImage;
public SeedsData(String itemName, String itemDescription, String itemPrice, int itemImage) {
this.itemName = itemName;
this.itemDescription = itemDescription;
this.itemPrice = itemPrice;
this.itemImage = itemImage;
}
public String getItemName() {
return itemName;
}
public String getItemDescription() {
return itemDescription;
}
public String getItemPrice() {
return itemPrice;
}
public int getItemImage() {
return itemImage;
}
}
MyAdapter3.java class code is here:
public class MyAdapter3 extends RecyclerView.Adapter<DiseasesViewHolder>{
private Context mContext;
private List<DiseasesData> myDiseasesList;
public MyAdapter3(Context mContext, List<DiseasesData> mySeedsList) {
this.mContext = mContext;
this.myDiseasesList = mySeedsList;
}
#Override
public DiseasesViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View mView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_row_item3,parent,false);
return new DiseasesViewHolder(mView);
}
#Override
public void onBindViewHolder(#NonNull final DiseasesViewHolder holder, final int position) {
holder.imageView.setImageResource(myDiseasesList.get(position).getItemImage());
holder.mTitle.setText(myDiseasesList.get(position).getItemName());
holder.mDescription.setText(myDiseasesList.get(position).getItemDescription());
holder.mPrice.setText(myDiseasesList.get(position).getItemPrice());
/* SeedsViewHolder.mCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext,SeedsDetailedActivity.class);
intent.putExtra("Image",mySeedsList.get(holder.getAdapterPosition()).getItemImage());
intent.putExtra("Description",mySeedsList.get(holder.getAdapterPosition()).getItemDescription());
mContext.startActivity(intent);
}
});*/
}
#Override
public int getItemCount() {
return myDiseasesList.size();
}
}
class DiseasesViewHolder extends RecyclerView.ViewHolder {
static ImageView imageView;
static TextView mTitle;
static TextView mDescription;
static TextView mPrice;
static CardView mCardView;
public DiseasesViewHolder(View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.ivImage);
mTitle = itemView.findViewById(R.id.tvTitle);
mDescription = itemView.findViewById(R.id.tvDescription);
mPrice = itemView.findViewById(R.id.tvPrice);
mCardView = itemView.findViewById(R.id.myCardView);
}
}
When i click on given link in error statements it brings my cursor to the beginning of these statements, so here is the specific critical part of my code(because cursor blinks at the start of this part when i click on exception)
holder.imageView.setImageResource(myDiseasesList.get(position).getItemImage());
Here is my Complete Stack trace List(from Run tab)
W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x94cd8b20)
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.e_agriculture10, PID: 3694
java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:587)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:422)
at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:840)
at android.content.res.Resources.loadDrawable(Resources.java:2110)
at android.content.res.Resources.getDrawable(Resources.java:700)
at androidx.appcompat.widget.ResourcesWrapper.getDrawable(ResourcesWrapper.java:130)
at androidx.appcompat.widget.TintResources.getDrawable(TintResources.java:46)
at androidx.core.content.ContextCompat.getDrawable(ContextCompat.java:465)
at androidx.appcompat.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:203)
at androidx.appcompat.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:191)
at androidx.appcompat.content.res.AppCompatResources.getDrawable(AppCompatResources.java:102)
at androidx.appcompat.widget.AppCompatImageHelper.setImageResource(AppCompatImageHelper.java:86)
at androidx.appcompat.widget.AppCompatImageView.setImageResource(AppCompatImageView.java:94)
at com.example.e_agriculture10.MyAdapter3.onBindViewHolder(MyAdapter3.java:37)
at com.example.e_agriculture10.MyAdapter3.onBindViewHolder(MyAdapter3.java:16)
at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)
at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)
at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
at androidx.recyclerview.widget.GridLayoutManager.layoutChunk(GridLayoutManager.java:557)
at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
at androidx.recyclerview.widget.GridLayoutManager.onLayoutChildren(GridLayoutManager.java:171)
at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3924)
at androidx.recyclerview.widget.RecyclerView.dispatchLayout(RecyclerView.java:3641)
at androidx.recyclerview.widget.RecyclerView.onLayout(RecyclerView.java:4194)
at android.view.View.layout(View.java:14817)
at android.view.ViewGroup.layout(ViewGroup.java:4631)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutHorizontal(LinearLayout.java:1660)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1436)
at android.view.View.layout(View.java:14817)
at android.view.ViewGroup.layout(ViewGroup.java:4631)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
at android.view.View.layout(View.java:14817)
at android.view.ViewGroup.layout(ViewGroup.java:4631)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14817)
at android.view.ViewGroup.layout(ViewGroup.java:4631)
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
at android.view.View.layout(View.java:14817)
at android.view.ViewGroup.layout(ViewGroup.java:4631)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutVertica
I/Process: Sending signal. PID: 3694 SIG: 9
Application terminated.
You need to provide more info on what the method getItemImage() is doing. Basically there's nothing clear.
Basically it's saying that your app is trying to use more memory than it's allowed by the system. When dealing with Bitmaps, memory management should be thought through within implementation. If it is only for displaying an Image on the screen try to use the Glide library
In your app/build.gradle add its dependency
dependencies{
implementation 'com.github.bumptech.glide:glide:4.9.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.9.0' }
And replace holder.imageView.setImageResource(myDiseasesList.get(position).getItemImage());
with
Glide.with(your_context)
.asBitmap()
.load("your/Image/Path") ///feed in path of the image
.centerCrop()
.into(holder.imageView);
The title is the error i've been receiving when I try (I think) to add an object to an arraylist
Here is the start of my code up to the onCreate method. I'm trying to use a button to add an object of "TimeTableEntries" to the "timetableItemsList" arraylist
*import statements*
public class Main extends AppCompatActivity {
TimetableEntriesClass timetableEntry;
private static final int Add_New_Item = Menu.FIRST;
private static final int Remove_Item = Menu.FIRST + 1;
private boolean addingNew = false;
private ListView timetableListView;
private EditText moduleCodeText;
private EditText DayOfWeekText;
private EditText StartTimeText;
private EditText DurationText;
private EditText SessionTypeText;
private EditText RoomText;
private Button Add;
private ArrayList<TimetableEntriesClass> timetableItemsList;
private TimetableEntriesAdapter aa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
timetableListView = (ListView)findViewById(R.id.myListView);
moduleCodeText = (EditText)findViewById(R.id.ModuleCode);
DayOfWeekText = (EditText)findViewById(R.id.DayOfWeek);
StartTimeText = (EditText)findViewById(R.id.StartTime);
DurationText = (EditText)findViewById(R.id.Duration);
SessionTypeText = (EditText)findViewById(R.id.SessionType);
RoomText = (EditText)findViewById(R.id.Room);
Add = (Button)findViewById(R.id.AddButton);
timetableItemsList = new ArrayList<TimetableEntriesClass>();
int resID = R.layout.timetable_view;
aa = new TimetableEntriesAdapter(this, resID, timetableItemsList);
timetableListView.setAdapter(aa);
Add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TimetableEntriesClass item = new TimetableEntriesClass(moduleCodeText.getText().toString(), DayOfWeekText.getText().toString(),
Integer.parseInt(StartTimeText.getText().toString() + ""), Integer.parseInt(DurationText.getText().toString() + ""),
SessionTypeText.getText().toString(), RoomText.getText().toString());
timetableItemsList.add(item);
aa.notifyDataSetChanged();
moduleCodeText.setText("#string/module_code");
DayOfWeekText.setText("#string/day_of_week");
StartTimeText.setText("#string/start_time");
DurationText.setText("#string/duration");
SessionTypeText.setText("#string/type_of_session");
RoomText.setText("#string/room");
}
});
registerForContextMenu(timetableListView);
}
04-04 15:19:11.499 2082-2119/com.example.daniel.mobileassignment E/Surface: getSlotFromBufferLocked: unknown buffer: 0xad2fefd0
04-04 15:19:13.523 2082-2082/com.example.daniel.mobileassignment W/ResourceType: No package identifier when getting value for resource number 0x00000001
04-04 15:19:13.532 2082-2082/com.example.daniel.mobileassignment D/AndroidRuntime: Shutting down VM
04-04 15:19:13.547 2082-2082/com.example.daniel.mobileassignment E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.daniel.mobileassignment, PID: 2082
android.content.res.Resources$NotFoundException: String resource ID #0x1
at android.content.res.Resources.getText(Resources.java:312)
I found the problem, it was the setText in my ArrayAdapter, it was looking for a String resource ID when it just needed an int!
I'm Using Fragments in my Android app, I have two class one is FirstClass.java which extends FragmentActivity and SecondClass extends Fragments and has button in its layout file.
So on Click of that button i'm calling "mylistener" function like this
<Button
android:id="#+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4.64"
android:text="Button"
android:onClick="mylistener"
/>
and FirstClass.java
public class FirstClass extends FragmentActivity {
Button btnSet1;
int mHour = 15;
int mMinute = 15;
/** This handles the message send from TimePickerDialogFragment on setting Time */
Handler mHandler = new Handler(){
#Override
public void handleMessage(Message m){
/** Creating a bundle object to pass currently set Time to the fragment */
Bundle b = m.getData();
/** Getting the Hour of day from bundle */
mHour = b.getInt("set_hour");
/** Getting the Minute of the hour from bundle */
mMinute = b.getInt("set_minute");
/** Displaying a short time message containing time set by Time picker dialog fragment */
Toast.makeText(getBaseContext(), b.getString("set_time"), Toast.LENGTH_SHORT).show();
btnSet1.getText().toString();
btnSet1.setText("set_time");
}
};
public void mylistener(View v){
/** Creating a bundle object to pass currently set time to the fragment */
Bundle b = new Bundle();
/** Adding currently set hour to bundle object */
b.putInt("set_hour", mHour);
/** Adding currently set minute to bundle object */
b.putInt("set_minute", mMinute);
/** Instantiating TimePickerDialogFragment */
TimePickerDialogFragment timePicker = new TimePickerDialogFragment(mHandler);
/** Setting the bundle object on timepicker fragment */
timePicker.setArguments(b);
/** Getting fragment manger for this activity */
FragmentManager fm = getSupportFragmentManager();
/** Starting a fragment transaction */
FragmentTransaction ft = fm.beginTransaction();
/** Adding the fragment object to the fragment transaction */
ft.add(timePicker, "time_picker");
/** Opening the TimePicker fragment */
ft.commit();
};
}
Now i'm able to get Timer Dialog on OnClick of Button, When tried to display that time format in Button getting NullPointer exception, I know this exception is because of button declaration in FirstClass FragmentActivity which is not present here, Please Help me to solve this issue.
03-09 10:40:53.222: E/AndroidRuntime(23637): java.lang.NullPointerException
03-09 10:40:53.222: E/AndroidRuntime(23637): at com.bikepooling.FirstClass$1.handleMessage(FirstClass.java:63)
03-09 10:40:53.222: E/AndroidRuntime(23637): at android.os.Handler.dispatchMessage(Handler.java:110)
03-09 10:40:53.222: E/AndroidRuntime(23637): at android.os.Looper.loop(Looper.java:193)
03-09 10:40:53.222: E/AndroidRuntime(23637): at android.app.ActivityThread.main(ActivityThread.java:5292)
03-09 10:40:53.222: E/AndroidRuntime(23637): at java.lang.reflect.Method.invokeNative(Native Method)
03-09 10:40:53.222: E/AndroidRuntime(23637): at java.lang.reflect.Method.invoke(Method.java:515)
03-09 10:40:53.222: E/AndroidRuntime(23637): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:824)
03-09 10:40:53.222: E/AndroidRuntime(23637): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
no need of this method,
public void mylistener(View v)
use this one
return new TimePickerDialog(Common.con, mTimeSetListener2, pHour, pMinute, false);
and also initialize the button for ex
btn = view.findviewbyid(...);
i hope will be work fine,
you have not initialised btnSet1
try doing this in onViewCreated:
btnSet1 = view.findViewById(R.id.b1);
My question is rather simple: how can one use(populate) Spinners in Fragments? Or better said, what is wrong with my code below? Adding Spinner as I did is as simple as it gets, but after trying in all the different ways, nothing worked. What is FragmentPagerAdapter has to do with Spinner? If I add the Spinner from a method declared somewhere else, the spinner is populated with no problems(for example if populating the spinner from a button).
Thanks in advance
public class MainActivity extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
public List<String> fragments = new Vector<String>();
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
private MySQLite database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager); // pager
mViewPager.setAdapter(mSectionsPagerAdapter);
// We initialise the database
database = new MySQLite(this);
Spinner spin = (Spinner)findViewById(R.id.spinner1);
List<String> toSpin = new ArrayList<String>();
toSpin.add("ONE");
toSpin.add("TWO");
toSpin.add("THREE");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,toSpin);
spin.setAdapter(adapter);
}
#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;
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
fragments.add(ConnectionFragment.class.getName());
fragments.add(DataFragment.class.getName());
}
#Override
public Fragment getItem(int position) {
// we need to instantiate the list of fragments
return Fragment.instantiate(getBaseContext(),
fragments.get(position));
}
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class ConnectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public ConnectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View connectionView = inflater.inflate(
R.layout.fragment_main_dummy, container, false);
return connectionView;
}
}
public static class DataFragment extends Fragment {
public DataFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View dataView = inflater.inflate(R.layout.fragment_linear,
container, false);
return dataView;
}
}
Logcat:
11-16 18:26:13.092: E/AndroidRuntime(16442): FATAL EXCEPTION: main
11-16 18:26:13.092: E/AndroidRuntime(16442): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.iwallet/com.example.iwallet.MainActivity}: java.lang.NullPointerException
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2071)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2096)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.ActivityThread.access$600(ActivityThread.java:138)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1207)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.os.Handler.dispatchMessage(Handler.java:99)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.os.Looper.loop(Looper.java:213)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.ActivityThread.main(ActivityThread.java:4787)
11-16 18:26:13.092: E/AndroidRuntime(16442): at java.lang.reflect.Method.invokeNative(Native Method)
11-16 18:26:13.092: E/AndroidRuntime(16442): at java.lang.reflect.Method.invoke(Method.java:511)
11-16 18:26:13.092: E/AndroidRuntime(16442): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
11-16 18:26:13.092: E/AndroidRuntime(16442): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
11-16 18:26:13.092: E/AndroidRuntime(16442): at dalvik.system.NativeStart.main(Native Method)
11-16 18:26:13.092: E/AndroidRuntime(16442): Caused by: java.lang.NullPointerException
11-16 18:26:13.092: E/AndroidRuntime(16442): at com.example.iwallet.MainActivity.onCreate(MainActivity.java:65)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.Activity.performCreate(Activity.java:5008)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
11-16 18:26:13.092: E/AndroidRuntime(16442): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2035)
11-16 18:26:13.092: E/AndroidRuntime(16442): ... 11 more
If you want to make your Spinner in your Fragment, maybe you must to declare in these Fragment in onCreatedView(). Not in onCreate() of your FragmentActivity.
And you can do it like this: Error populating spinner in a fragment
I'm trying to create my first Android App (a game) but I'm having some difficulties getting started.
When I run my code I get this error log:
05-25 02:41:51.022: WARN/dalvikvm(634): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
05-25 02:41:51.040: ERROR/AndroidRuntime(634): FATAL EXCEPTION: main
05-25 02:41:51.040: ERROR/AndroidRuntime(634): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.stickfigs.nmg/com.stickfigs.nmg.NMG}: java.lang.NullPointerException
05-25 02:41:51.040: ERROR/AndroidRuntime(634): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
05-25 02:41:51.040: ERROR/AndroidRuntime(634): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
05-25 02:41:51.040: ERROR/AndroidRuntime(634): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
05-25 02:41:51.040: ERROR/AndroidRuntime(634): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
05-25 02:41:51.040: ERROR/AndroidRuntime(634): at android.os.Handler.dispatchMessage(Handler.java:99)
05-25 02:41:51.040: ERROR/AndroidRuntime(634): at android.os.Looper.loop(Looper.java:123)
05-25 02:41:51.040: ERROR/AndroidRuntime(634): at android.app.ActivityThread.main(ActivityThread.java:4627)
05-25 02:41:51.040: ERROR/AndroidRuntime(634): at java.lang.reflect.Method.invokeNative(Native Method)
05-25 02:41:51.040: ERROR/AndroidRuntime(634): at java.lang.reflect.Method.invoke(Method.java:521)
05-25 02:41:51.040: ERROR/AndroidRuntime(634): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-25 02:41:51.040: ERROR/AndroidRuntime(634): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-25 02:41:51.040: ERROR/AndroidRuntime(634): at dalvik.system.NativeStart.main(Native Method)
05-25 02:41:51.040: ERROR/AndroidRuntime(634): Caused by: java.lang.NullPointerException
05-25 02:41:51.040: ERROR/AndroidRuntime(634): at com.stickfigs.nmg.NMG.onCreate(NMG.java:32)
05-25 02:41:51.040: ERROR/AndroidRuntime(634): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-25 02:41:51.040: ERROR/AndroidRuntime(634): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
05-25 02:41:51.040: ERROR/AndroidRuntime(634): ... 11 more
05-25 02:41:51.062: WARN/ActivityManager(59): Force finishing activity com.stickfigs.nmg/.NMG
I think the problem is this "thread exiting with uncaught exception" part, I have no idea what the exception could be or what's causing it.
Here is my code:
NMGView.java:
package com.stickfigs.NMG;
import android.content.Context;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
class NMGView extends SurfaceView implements SurfaceHolder.Callback {
class NMGThread extends Thread {
//State-tracking constants
public static final int STATE_LOSE = 1;
public static final int STATE_PAUSE = 2;
public static final int STATE_READY = 3;
public static final int STATE_RUNNING = 4;
public static final int STATE_WIN = 5;
/** The state of the game. One of READY, RUNNING, PAUSE, LOSE, or WIN */
private int mode;
/** Handle to the surface manager object we interact with */
private SurfaceHolder surfaceHolder;
public NMGThread(SurfaceHolder surfaceHolderc, Context contextc) {
// get handles to some important objects
surfaceHolder = surfaceHolderc;
context = contextc;
}
/**
* Restores game state from the indicated Bundle. Typically called when
* the Activity is being restored after having been previously
* destroyed.
*
* #param savedState Bundle containing the game state
*/
public synchronized void restoreState(Bundle savedState) {
synchronized (surfaceHolder) {
setState(STATE_PAUSE);
}
}
/**
* Sets the game mode. That is, whether we are running, paused, in the
* failure state, in the victory state, etc.
*
* #param mode one of the STATE_* constants
* #param message string to add to screen or null
*/
public void setState(int modec) {
synchronized (surfaceHolder) {
mode = modec;
}
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
/** Handle to the application context, used to e.g. fetch Drawables. */
private Context context;
/** The thread that actually draws the animation */
private NMGThread thread;
public NMGView(Context context, AttributeSet attrs) {
super(context, attrs);
// register our interest in hearing about changes to our surface
SurfaceHolder holder = getHolder();
holder.addCallback(this);
// create thread only; it's started in surfaceCreated()
thread = new NMGThread(holder, context);
setFocusable(true); // make sure we get key events
}
/**
* Fetches the animation thread corresponding to this LunarView.
*
* #return the animation thread
*/
public NMGThread getThread() {
return thread;
}
}
NMG.java:
package com.stickfigs.nmg;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import com.stickfigs.nmg.NMGView.NMGThread;
public class NMG extends Activity {
/** Called when the activity is first created. */
/** A handle to the thread that's actually running the animation. */
private NMGThread nMGThread;
/** A handle to the View in which the game is running. */
private NMGView nMGView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Turn off the window's title bar
// TODO Turn off the status bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
// tell system to use the layout defined in our XML file
setContentView(R.layout.nmg_layout);
// get handles to the LunarView from XML, and its LunarThread
nMGView = (NMGView) findViewById(R.id.nmg);
nMGThread = nMGView.getThread();
if (savedInstanceState == null) {
// we were just launched: set up a new game
nMGThread.setState(NMGThread.STATE_READY);
Log.w(this.getClass().getName(), "SIS is null");
} else {
// we are being restored: resume a previous game
nMGThread.restoreState(savedInstanceState);
Log.w(this.getClass().getName(), "SIS is nonnull");
}
}
}
UPDATE: Here is my R.java and nmg_layout.xml:
R.java:
package com.stickfigs.nmg;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int icon=0x7f020000;
}
public static final class id {
public static final int nmg=0x7f050000;
}
public static final class layout {
public static final int nmg_layout=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f040001;
public static final int hello=0x7f040000;
}
}
nmg_layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.stickfigs.nmg.NMGView
android:id="#+id/nmg"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</FrameLayout>
If you look through the stack trace, you will see a "Caused by..." line (sometimes more than one). The last one of those is the important one. It says that there was a null pointer exception on line 32 of NMG.java. That line, and the line before it, are:
nMGView = (NMGView) findViewById(R.id.nmg);
nMGThread = nMGView.getThread();
Evidently, no view with id R.id.nmg is in layout R.layout.nmg_layout. That's what's causing your problem.
In your XML file, the R.id.nmg do exist.
So I think the problem is caused by inflating the NMGView object from the resource.
You should examine your NMGView source code, especially in its constructor.
If you are using "multiDexEnabled true" in your "build.gradle(Module:app)" , remove this line from "defaultConfig" and sync project.
It works in my case !!!
This problems happens because most of the time the SurfaceView onDraw() method is running when you destroy the surfaceView then you get a NULL POINTER ERROR because the canvas doesn´t exist by that moment. I have fixed this problem catching all the drawing stuff with the NullPointerException:
#Override
public void onDraw(Canvas canvas) {
try {
//Drawing Stuff
}catch(NullPointerException e){
Log.e("NULL POINTER EXCEPTION","Canvas NULL POINTER");
}
}
If you implement onPause(), onDestroy() methods in your Main activity you will get the following order: first: E/onPause﹕ ON PAUSE --> next E/surfaceDestroyed﹕ SURFACE DESTROYED --> E/NULL POINTER EXCEPTION﹕ Canvas NULL POINTER --> finally
E/onDestroy﹕ ON DESTROY
this is surfaceDestroyed method I am using:
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
Log.e("surfaceDestroyed", "SURFACE DESTROYED ");
thread.setRunning(false);
try {
//thread.setRunning(false);
thread.join();
} catch (InterruptedException e) {
Log.e("Surface Thread Stopped","SURFACE THREAD STOPPED");
}
}