Runtime Exception unable to start MainActivity - java

I'm trying to test my Android app on a new phone I've just purchased with Android 4.2. It runs every other app I test, and this particular app also works on other devices. When I try to run the code it's giving me the following errors:
> 02-23 12:15:08.532: E/AndroidRuntime(5431): FATAL EXCEPTION: main
02-23 12:15:08.532: E/AndroidRuntime(5431): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.antiquity/com.example.antiquity.MainActivity}: java.lang.NullPointerException
02-23 12:15:08.532: E/AndroidRuntime(5431): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
02-23 12:15:08.532: E/AndroidRuntime(5431): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
02-23 12:15:08.532: E/AndroidRuntime(5431): at android.app.ActivityThread.access$600(ActivityThread.java:162)
02-23 12:15:08.532: E/AndroidRuntime(5431): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
02-23 12:15:08.532: E/AndroidRuntime(5431): at android.os.Handler.dispatchMessage(Handler.java:107)
02-23 12:15:08.532: E/AndroidRuntime(5431): at android.os.Looper.loop(Looper.java:194)
02-23 12:15:08.532: E/AndroidRuntime(5431): at android.app.ActivityThread.main(ActivityThread.java:5371)
02-23 12:15:08.532: E/AndroidRuntime(5431): at java.lang.reflect.Method.invokeNative(Native Method)
02-23 12:15:08.532: E/AndroidRuntime(5431): at java.lang.reflect.Method.invoke(Method.java:525)
02-23 12:15:08.532: E/AndroidRuntime(5431): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
02-23 12:15:08.532: E/AndroidRuntime(5431): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
02-23 12:15:08.532: E/AndroidRuntime(5431): at dalvik.system.NativeStart.main(Native Method)
02-23 12:15:08.532: E/AndroidRuntime(5431): Caused by: java.lang.NullPointerException
02-23 12:15:08.532: E/AndroidRuntime(5431): at com.example.antiquity.MainActivity.setUpLocation(MainActivity.java:127)
02-23 12:15:08.532: E/AndroidRuntime(5431): at com.example.antiquity.MainActivity.onCreate(MainActivity.java:96)
02-23 12:15:08.532: E/AndroidRuntime(5431): at android.app.Activity.performCreate(Activity.java:5139)
02-23 12:15:08.532: E/AndroidRuntime(5431): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1084)
02-23 12:15:08.532: E/AndroidRuntime(5431): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
02-23 12:15:08.532: E/AndroidRuntime(5431): ... 11 more
Now I've checked line 127 and even removing that and leaving an empty line will still cause this error relating to line 127.
My MainActivity.class code:
public class MainActivity extends Activity {
private GoogleMap map;
Intent data;
MonumentsDatabase monDatabase;
int _id;
int _lat;
int _lng;
String _title;
LatLng MARKERS;
LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
Intent data = new Intent(MainActivity.this, DisplayData.class);
startActivity(data);
}
});
setUpLocation();
locationManager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if ( !locationManager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
disabledGPS();
}
map.setMyLocationEnabled(true);
}
public void setUpLocation() {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location myLocation = locationManager.getLastKnownLocation(provider);
double latitude = myLocation.getLatitude();
double longitude = myLocation.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.animateCamera(CameraUpdateFactory.zoomTo(40));
}
private void disabledGPS() {
final AlertDialog.Builder gpsDisabled = new AlertDialog.Builder(this);
gpsDisabled.setMessage("This app requires GPS to be enabled. Do you wish to continue?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog mainAlert = gpsDisabled.create();
mainAlert.show();
}
/**
public boolean onMarkerClick(Marker marker) {
//Intent data = new Intent(this, DisplayData.class);
// TODO Auto-generated method stub
startActivity(data);
return true;
}
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void createDatabase() {
monDatabase = new MonumentsDatabase(this);
try {
monDatabase.createDatabase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
monDatabase.openDatabase();
}catch(SQLException sqle){
throw sqle;
}
}
}
I find it strange how it works on one device and then crashes on another.
Thanks for any help! :)
EDIT:
activity_layout.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity" >
<fragment
android:id="#+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
AndroidManifest.xml file:
Not sure why, but it isn't liking the indents.
So sorry for the link but:
http://pastebin.com/kd4EpP4W

I think your
Location myLocation = locationManager.getLastKnownLocation(provider);
line returning null.
Please check this answer. It might be helpful

Here, If you are targeting your minimum SDK version < 12 in your manifest file then you can't use MapFragment. So must be sure that your minimum SDK version is above or equals to 12. And if it is not then change in your xml file from
android:name="com.google.android.gms.maps.MapFragment"
to
android:name="com.google.android.gms.maps.SupportMapFragment"
And also in your activity change from
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
to
map=((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
And also If you're using fragments on older devices (pre Honeycomb) you should always extend your Activity from FragmentActivity.
Also import android.support.v4.app.FragmentActivity and for more information on this go to my this answer

If I don't mistake, fragments should be used in Activity which extends either Fragment or FragmentActivity. Probably something is wrong with map

Related

Getting java.lang.NullPointerException when I try to use maps

First of all, I'm using Android Studio and it's my first time using maps.
I created a project, with a Navigation Drawer Activity.
File> New Project > Next > Next> Switched "Navigation Drawer Activity" and clicked next > Finish.
After, I clicked in the project with the right button > new > activity > google > google maps activity.
I put google api maps key in google_maps_api.xml.
So I opened MainActivity, and type the following inside OnCreateView function:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_maps, container, false);
setUpMapIfNeeded();
return rootView;
}
then I add after that the following two functions:
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (mMap == null) {
// Try to obtain the map from the SupportMapFragment.
mMap = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
// Check if we were successful in obtaining the map.
if (mMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
}
Everytime I try to execute it, I get a null pointer exception. Here is the complete error message:
04-14 19:44:40.204 4390-4390/ct.ufrn.br.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: ct.ufrn.br.myapplication, PID: 4390
java.lang.RuntimeException: Unable to start activity ComponentInfo{ct.ufrn.br.myapplication/ct.ufrn.br.myapplication.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at ct.ufrn.br.myapplication.MainActivity$PlaceholderFragment.onCreateView(MainActivity.java:142)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:548)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1194)
at android.app.Activity.performStart(Activity.java:5258)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2171)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
at android.app.ActivityThread.access$800(ActivityThread.java:139)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Do you know how to solve it?
obs: I tryied the same with a blank activity (in onCreate method, instead onCreateView), and it worked well.
Here is the activity_maps.xml:
<fragment 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:id="#+id/map"
tools:context="ct.ufrn.br.myapplication.MapsActivity"
android:name="com.google.android.gms.maps.SupportMapFragment" />
I solved replacing
mMap = ((SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
with
mMap = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)).getMap();

Unable to start activity: NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
Hi I am encountering a null pointer error when I click on the activity Links. The purpose of my feature is to call a list of links in the form of list view. Below is the logcat and as far as I understand it is coming from my onItemClickListener, but I can't seem to point out the null error.:
sitesList.setOnItemClickListener(new OnItemClickListener()
Links.java
package com.example.sgrecipe;
import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class Links extends Activity {
private SitesAdapter mAdapter;
private ListView sitesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("StackSites", "OnCreate()");
setContentView(R.layout.activity_main);
//Get reference to our ListView
sitesList = (ListView)findViewById(R.id.sitesList);
//Set the click listener to launch the browser when a row is clicked.
sitesList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,long id) {
String url = mAdapter.getItem(pos).getLink();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
/*
* If network is available download the xml from the Internet.
* If not then try to use the local file from last time.
*/
if(isNetworkAvailable()){
Log.i("StackSites", "starting download Task");
SitesDownloadTask download = new SitesDownloadTask();
download.execute();
}else{
mAdapter = new SitesAdapter(getApplicationContext(), -1, SitesXmlPullParser.getStackSitesFromFile(Links.this));
sitesList.setAdapter(mAdapter);
}
}
//Helper method to determine if Internet connection is available.
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
/*
* AsyncTask that will download the xml file for us and store it locally.
* After the download is done we'll parse the local file.
*/
private class SitesDownloadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
//Download the file
try {
Downloader.DownloadFromUrl("https://dl.dropboxusercontent.com/u/5724095/XmlParseExample/stacksites.xml", openFileOutput("StackSites.xml", Context.MODE_PRIVATE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
//setup our Adapter and set it to the ListView.
mAdapter = new SitesAdapter(Links.this, -1, SitesXmlPullParser.getStackSitesFromFile(Links.this));
sitesList.setAdapter(mAdapter);
Log.i("StackSites", "adapter size = "+ mAdapter.getCount());
}
}
}
activity_links.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Links" >
<ListView
android:id="#+id/sitesList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
row_site.xml (for the listview)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp" >
<ProgressBar
android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/iconImg"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginRight="8dp" />
<TextView
android:id="#+id/nameTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/iconImg"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/aboutTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/iconImg"
android:textSize="12sp"
android:layout_below="#id/nameTxt"
/>
</RelativeLayout>
Here is the logcat:
02-23 15:13:10.856: E/AndroidRuntime(8201): FATAL EXCEPTION: main
02-23 15:13:10.856: E/AndroidRuntime(8201): Process: com.example.sgrecipe, PID: 8201
02-23 15:13:10.856: E/AndroidRuntime(8201): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sgrecipe/com.example.sgrecipe.Links}: java.lang.NullPointerException
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2292)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2350)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.access$800(ActivityThread.java:163)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1257)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.os.Handler.dispatchMessage(Handler.java:102)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.os.Looper.loop(Looper.java:157)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.main(ActivityThread.java:5335)
02-23 15:13:10.856: E/AndroidRuntime(8201): at java.lang.reflect.Method.invokeNative(Native Method)
02-23 15:13:10.856: E/AndroidRuntime(8201): at java.lang.reflect.Method.invoke(Method.java:515)
02-23 15:13:10.856: E/AndroidRuntime(8201): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
02-23 15:13:10.856: E/AndroidRuntime(8201): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
02-23 15:13:10.856: E/AndroidRuntime(8201): at dalvik.system.NativeStart.main(Native Method)
02-23 15:13:10.856: E/AndroidRuntime(8201): Caused by: java.lang.NullPointerException
02-23 15:13:10.856: E/AndroidRuntime(8201): at com.example.sgrecipe.Links.onCreate(Links.java:36)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.Activity.performCreate(Activity.java:5389)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2256)
Any help is really appreciate, thank you!
Change following line
setContentView(R.layout.activity_main);
to
setContentView(R.layout.activity_links);
Seems like your using different layouts:
setContentView(R.layout.activity_main);
vs
activity_links.xml

Null pointer exception - loading a new activity from fragment

I ran into a null pointer exception when trying to load a new activity from a fragment - it essentially tells me an unexpected error has occurred. Below is the log cat message:
08-21 11:57:14.801: E/AndroidRuntime(1245): FATAL EXCEPTION: main
08-21 11:57:14.801: E/AndroidRuntime(1245): Process: com.dooba.beta, PID: 1245
08-21 11:57:14.801: E/AndroidRuntime(1245): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dooba.beta/com.dooba.beta.matchOptionActivity}: java.lang.NullPointerException
08-21 11:57:14.801: E/AndroidRuntime(1245): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
08-21 11:57:14.801: E/AndroidRuntime(1245): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
08-21 11:57:14.801: E/AndroidRuntime(1245): at android.app.ActivityThread.access$800(ActivityThread.java:135)
08-21 11:57:14.801: E/AndroidRuntime(1245): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
08-21 11:57:14.801: E/AndroidRuntime(1245): at android.os.Handler.dispatchMessage(Handler.java:102)
08-21 11:57:14.801: E/AndroidRuntime(1245): at android.os.Looper.loop(Looper.java:136)
08-21 11:57:14.801: E/AndroidRuntime(1245): at android.app.ActivityThread.main(ActivityThread.java:5017)
08-21 11:57:14.801: E/AndroidRuntime(1245): at java.lang.reflect.Method.invokeNative(Native Method)
08-21 11:57:14.801: E/AndroidRuntime(1245): at java.lang.reflect.Method.invoke(Method.java:515)
08-21 11:57:14.801: E/AndroidRuntime(1245): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
08-21 11:57:14.801: E/AndroidRuntime(1245): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
08-21 11:57:14.801: E/AndroidRuntime(1245): at dalvik.system.NativeStart.main(Native Method)
08-21 11:57:14.801: E/AndroidRuntime(1245): Caused by: java.lang.NullPointerException
08-21 11:57:14.801: E/AndroidRuntime(1245): at com.dooba.beta.matchOptionActivity.onCreate(matchOptionActivity.java:29)
08-21 11:57:14.801: E/AndroidRuntime(1245): at android.app.Activity.performCreate(Activity.java:5231)
08-21 11:57:14.801: E/AndroidRuntime(1245): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-21 11:57:14.801: E/AndroidRuntime(1245): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
08-21 11:57:14.801: E/AndroidRuntime(1245): ... 11 more
Below is the fragment activity code (the place where the new intent activity is called)
public class Fragment1 extends Fragment {
private String currentUserId;
private ArrayAdapter<String> namesArrayAdapter;
private ArrayList<String> names;
private ListView usersListView;
private Button logoutButton;
String userGender = ParseUser.getCurrentUser().getString("Gender");
String activityName = ParseUser.getCurrentUser().getString("ActivityName");
Number maxDistance = ParseUser.getCurrentUser().getNumber("Maximum_Distance");
String userLookingGender = ParseUser.getCurrentUser().getString("Looking_Gender");
Number minimumAge = ParseUser.getCurrentUser().getNumber("Minimum_Age");
Number maximumAge = ParseUser.getCurrentUser().getNumber("Maximum_Age");
Number userage = ParseUser.getCurrentUser().getNumber("Age");
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setConversationsList();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment1_layout, container, false);
Button newPage = (Button)view.findViewById(R.id.btnMatchConfirm);
newPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getActivity(), matchOptionActivity.class);
startActivity(intent);
}
});
return view;
}
private void setConversationsList() {
currentUserId = ParseUser.getCurrentUser().getObjectId();
names = new ArrayList<String>();
// String userActivitySelectionName = null;
ParseQuery<ParseUser> query = ParseUser.getQuery();
// query.whereEqualTo("ActivityName",userActivitySelectionName);
query.whereNotEqualTo("objectId", ParseUser.getCurrentUser().getObjectId());
// users with Gender = currentUser.Looking_Gender
query.whereEqualTo("Gender", userLookingGender);
// users with Looking_Gender = currentUser.Gender
query.whereEqualTo("Looking_Gender", userGender);
query.setLimit(1);
query.whereEqualTo("ActivityName", activityName);
// query.whereGreaterThanOrEqualTo("Age", minimumAge);
// query.whereLessThanOrEqualTo("Age", maximumAge);
query.orderByDescending("Name");
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> userList, ParseException e) {
if (e == null) {
for (int i=0; i<userList.size(); i++) {
names.add(userList.get(i).get("Name").toString());
names.add(userList.get(i).get("Headline").toString());
names.add(userList.get(i).get("Age").toString());
names.add(userList.get(i).get("ActivityName").toString());
// names.add(userList.get(i).getParseObject("ProfilePicture").;
}
usersListView = (ListView)getActivity().findViewById(R.id.userlistview1);
namesArrayAdapter =
new ArrayAdapter<String>(getActivity().getApplicationContext(),
R.layout.user_list_item, names);
usersListView.setAdapter(namesArrayAdapter);
usersListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
openConversation(names, i);
}
});
} else {
Toast.makeText(getActivity().getApplicationContext(),
"Error loading user list",
Toast.LENGTH_LONG).show();
}
}
});
}
public void openConversation(ArrayList<String> names, int pos) {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("Name", names.get(pos));
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> user, ParseException e) {
if (e == null) {
Intent intent = new Intent(getActivity().getApplicationContext(), MessagingActivity.class);
intent.putExtra("RECIPIENT_ID", user.get(0).getObjectId());
startActivity(intent);
} else {
Toast.makeText(getActivity().getApplicationContext(),
"Error finding that user",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
Below is the code for the matchOption activity (the activity that is called upon button click)
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.matchoption);
final ImageView idrinks = (ImageView) this.findViewById(R.id.icasual);
idrinks.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
matchOptionActivity.this.startActivity(new Intent(matchOptionActivity.this, MessagingActivity.class));
}
});
}
}
Furthermore, I am using Parse to populate my list of users, and I would like to know how I would be hide the confirm button in the event that the list is empty.
Thanks in advance.
Update
below is the fragment XML file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/blue_bac3"
android:orientation="vertical" >
<ListView
android:id="#+id/userlistview1"
android:layout_width="match_parent"
android:layout_height="400dp"
android:textColor="#ffffff"
android:divider="#null"
>
</ListView>
<Button
android:id="#+id/btnMatchConfirm"
android:layout_width="100dp"
android:layout_height="50dp"
android:background="#drawable/gray_bac"
android:layout_below="#+id/userlistview1"
android:layout_centerHorizontal="true"
android:layout_marginTop="13dp"
android:text="Confirm" />
</RelativeLayout>
I don't have reputation to add comment...Can you also provide the matchoption xml for further analysis or check the onClick() method. looks like some issue over there
Caused by: java.lang.NullPointerException
08-21 11:57:14.801: E/AndroidRuntime(1245): at com.dooba.beta.matchOptionActivity.onCreate(matchOptionActivity.java:29)
I guess you need to change the code
from this
idrinks.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
matchOptionActivity.this.startActivity(new Intent(matchOptionActivity.this, MessagingActivity.class));
}
});
to this
idrinks.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(this,MessagingActivity.class);
i.startActivity(new Intent(matchOptionActivity.this, MessagingActivity.class));
}
});

Android application has stopped working -eclipse

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.

Force close error on application when button is pressed

So whenever I click the button on the startup page, it gives me a force close error. Here's the class for the main.xml layout file:
public class ForeverAloneActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnstrt = (Button) findViewById(R.id.toq1);
btnstrt.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
Intent frstq = new Intent(v.getContext(), QuestionOne.class);
startActivityForResult(frstq, 0);
And this is what I believe is producing the error. This class is related to the page that that when pressing the button on the startup page, you are taken to:
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView (R.layout.frstq);
Button startQ2 = (Button) findViewById(R.id.toq2);
startQ2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
Intent toQ2 = new Intent(v.getContext(), QuestionTwo.class);
final EditText number = (EditText) findViewById(R.id.editText1);
final Toast error = Toast.makeText(QuestionOne.this, "Please insert a value", Toast.LENGTH_SHORT);
if (number.getText().toString().equals("")) {error.show();
}else{
startActivityForResult(toQ2, 0);}
That if statement is there as on the next page, there is an EditText box. I tried to make it so that if there is nothing in the EditText box, it displays a toast message saying "Please insert a value". Until an integer is put into the EditText box, then the button will not work.
If someone can help, it will be much appreciated.
Logcat:
04-07 19:33:58.199: W/dalvikvm(362): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
04-07 19:33:58.221: E/AndroidRuntime(362): FATAL EXCEPTION: main
04-07 19:33:58.221: E/AndroidRuntime(362): android.content.ActivityNotFoundException: Unable to find explicit activity class {com.kenning.foreveralone/com.kenning.foreveralone.QuestionOne}; have you declared this activity in your AndroidManifest.xml?
04-07 19:33:58.221: E/AndroidRuntime(362): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1404)
04-07 19:33:58.221: E/AndroidRuntime(362): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1378)
04-07 19:33:58.221: E/AndroidRuntime(362): at android.app.Activity.startActivityForResult(Activity.java:2817)
04-07 19:33:58.221: E/AndroidRuntime(362): at com.kenning.foreveralone.ForeverAloneActivity$1.onClick(ForeverAloneActivity.java:22)
04-07 19:33:58.221: E/AndroidRuntime(362): at android.view.View.performClick(View.java:2408)
04-07 19:33:58.221: E/AndroidRuntime(362): at android.view.View$PerformClick.run(View.java:8816)
04-07 19:33:58.221: E/AndroidRuntime(362): at android.os.Handler.handleCallback(Handler.java:587)
04-07 19:33:58.221: E/AndroidRuntime(362): at android.os.Handler.dispatchMessage(Handler.java:92)
04-07 19:33:58.221: E/AndroidRuntime(362): at android.os.Looper.loop(Looper.java:123)
04-07 19:33:58.221: E/AndroidRuntime(362): at android.app.ActivityThread.main(ActivityThread.java:4627)
04-07 19:33:58.221: E/AndroidRuntime(362): at java.lang.reflect.Method.invokeNative(Native Method)
04-07 19:33:58.221: E/AndroidRuntime(362): at java.lang.reflect.Method.invoke(Method.java:521)
04-07 19:33:58.221: E/AndroidRuntime(362): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
04-07 19:33:58.221: E/AndroidRuntime(362): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
04-07 19:33:58.221: E/AndroidRuntime(362): at dalvik.system.NativeStart.main(Native Method)
are you adding QuestionTwo in manifiest file ?
check your error - have you declared this activity in your AndroidManifest.xml?
Declare your activity in manifeast file. It seems you forgetted that
<activity android:name="QuestionTwo" />
also dont forget to include every activity in your manifeast file
Hey have you added the QuestionTwo class as an activity in menifest file. If after adding the
Intent toQ2 = new Intent(YourCurrentActivity.this,QuestionTwo.class);
then you must have not added the activity in menifest.B'coz it clearly shows in the log that Activity is not found. You have to declare the activity in menifest file.
Hope you'll get run your app.

Categories