Null pointer exception - loading a new activity from fragment - java

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));
}
});

Related

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.hometools/com.example.hometools.HometoolsActivity

I'm getting an error message when I try to run my project. This is for a college task, something simple. I believe the XML is ok.
Let me know if you need anything else to help me, I'm just a beginner.
package com.example.hometools;
import com.example.hometools.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.CheckBox;
public class HometoolsActivity extends Activity {
//Tela Principal
Button button1;
Button button2;
Button button3;
Button button4;
Button button5;
//tinta
EditText editText1t1;
EditText editText2t1;
EditText editText3t1;
EditText editText4t1;
Button button1t1;
Button button2t1; // voltar
//piso
EditText editText1t2;
EditText editText2t2;
EditText editText3t2;
Button button1t2;
Button button2t2; // voltar
//btu
EditText editText1t3;
EditText editText2t3;
EditText editText3t3;
EditText editText4t3;
CheckBox checkBox1t3;
Button button1t3;
Button button2t3; // voltar
//aquecedor
EditText editText1t4;
EditText editText2t4;
EditText editText3t4;
EditText editText4t4;
EditText editText5t4;
EditText editText6t4;
Button button1t4;
Button button2t4; // voltar
//caixa
EditText editText1t5;
EditText editText2t5;
EditText editText3t5;
Button button1t5;
Button button2t5; // voltar
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
controlePrincipal();
}
public void controlePrincipal() {
setContentView(R.layout.activity_hometools);
controleTinta(); //controla tinta
controlePiso(); //controla piso
controleBtu(); // controla btu
controleAquecedor(); // controla aquecedor
controleCaixa(); // controla caixa
}
public void controleTinta(){
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener (new OnClickListener() {
#Override
public void onClick(View arg0){
setContentView(R.layout.tinta);
editText1t1 = (EditText) findViewById(R.id.editText1t1);
editText2t1 = (EditText) findViewById(R.id.editText2t1);
editText3t1 = (EditText) findViewById(R.id.editText3t1);
editText4t1 = (EditText) findViewById(R.id.editText4t1);
button1t1 = (Button) findViewById(R.id.button1t1);
button1t1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
double rendimento, quantidade,demao, area, valor_arred;
//entrada de dados
area=Double.parseDouble(editText1t1.getText().toString()) ;
demao=Double.parseDouble(editText2t1.getText().toString());
rendimento=Double.parseDouble(editText3t1.getText().toString());
quantidade = area*demao/rendimento;
quantidade = quantidade*1.1;
//arredondando o valor para cima
valor_arred = Math.ceil(quantidade);
//saída de dados
editText4t1.setText(String.valueOf(valor_arred));
}
});
button2t1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
controlePrincipal();
}
});
}
});
}
public void controlePiso(){
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener (new OnClickListener() {
#Override
public void onClick(View arg0){
setContentView(R.layout.piso);
editText1t2 = (EditText) findViewById(R.id.editText1t2);
editText2t2 = (EditText) findViewById(R.id.editText2t2);
editText3t2 = (EditText) findViewById(R.id.editText3t2);
button1t2 = (Button) findViewById(R.id.button1t2);
button1t2.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
double area, tamanho, piso, valor_arred;
//entrada de dados
area=Double.parseDouble(editText1t2.getText().toString()) ;
tamanho=Double.parseDouble(editText2t2.getText().toString());
piso=area/tamanho;
piso=piso*1.1;
//arredondando o valor para cima.
valor_arred = Math.ceil(piso);
//saída de dados
editText3t2.setText(String.valueOf(valor_arred));
}
});
button2t2.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
controlePrincipal();
}
});
}
});
}
public void controleBtu(){
button3 = (Button) findViewById(R.id.button3);
button3.setOnClickListener (new OnClickListener() {
#Override
public void onClick(View arg0){
setContentView(R.layout.btu);
editText1t3 = (EditText) findViewById(R.id.editText1t3);
editText2t3 = (EditText) findViewById(R.id.editText2t3);
editText3t3 = (EditText) findViewById(R.id.editText3t3);
editText4t3 = (EditText) findViewById(R.id.editText4t3);
button1t3 = (Button) findViewById(R.id.button1t3);
checkBox1t3 = (CheckBox) findViewById(R.id.checkBox1t3);
button1t3.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
double area, valor_arred, BTU;
int pessoas, eletronicos;
//entrada de dados
area=Double.parseDouble(editText1t3.getText().toString()) ;
pessoas=Integer.parseInt(editText2t3.getText().toString());
eletronicos=Integer.parseInt(editText3t3.getText().toString());
//saída de dados
if (checkBox1t3.isChecked()) {
BTU=area*800+pessoas*800+eletronicos*800;
}
else {
BTU=area*600+pessoas*600+eletronicos*600;
}
valor_arred=Math.ceil(BTU);
editText4t3.setText(String.valueOf(valor_arred));
}
});
button2t3.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
controlePrincipal();
}
});
}
});
}
public void controleAquecedor(){
button4 = (Button) findViewById(R.id.button4);
button4.setOnClickListener (new OnClickListener() {
#Override
public void onClick(View arg0){
setContentView(R.layout.aquecedor);
editText1t4 = (EditText) findViewById(R.id.editText1t4);
editText2t4 = (EditText) findViewById(R.id.editText2t4);
editText3t4 = (EditText) findViewById(R.id.editText3t4);
editText4t4 = (EditText) findViewById(R.id.editText4t4);
editText5t4 = (EditText) findViewById(R.id.editText5t4);
editText6t4 = (EditText) findViewById(R.id.editText6t4);
button1t4 = (Button) findViewById(R.id.button1t4);
button1t4.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
int a,b,c,d;
double qnec,vazao,vazaoaq,quant,quantarr;
//entrada de dados
a=Integer.parseInt(editText1t4.getText().toString()) ;
b=Integer.parseInt(editText2t4.getText().toString()) ;
c=Integer.parseInt(editText3t4.getText().toString()) ;
d=Integer.parseInt(editText4t4.getText().toString()) ;
vazaoaq=Double.parseDouble(editText5t4.getText().toString()) ;
vazao=12*a+6*b+9*c+15*d;
qnec=vazao/2;
quant=qnec/vazaoaq;
quantarr=Math.ceil(quant);
//saída de dados
editText6t4.setText(String.valueOf(quantarr));
}
});
button2t4.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
controlePrincipal();
}
});
}
});
}
public void controleCaixa(){
button1t5 = (Button) findViewById(R.id.button1t5);
button1t5.setOnClickListener (new OnClickListener() {
#Override
public void onClick(View arg0){
setContentView(R.layout.caixa);
editText1t5 = (EditText) findViewById(R.id.editText1t5);
editText2t5 = (EditText) findViewById(R.id.editText2t5);
editText3t5 = (EditText) findViewById(R.id.editText3t5);
button1t5 = (Button) findViewById(R.id.button1t5);
button1t5.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
double minimo, intervalo, valor_arred;
int pessoas;
//entrada de dados
intervalo=Double.parseDouble(editText1t5.getText().toString()) ;
pessoas=Integer.parseInt(editText2t5.getText().toString());
minimo=pessoas*intervalo*150;
//arredondando o valor para cima.
valor_arred = Math.ceil(minimo);
//saída de dados
editText3t5.setText(String.valueOf(valor_arred));
}
});
button2t5.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0){
controlePrincipal();
}
});
}
});
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
tools:context="${relativePackage}.${activityClass}" >
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginRight="16dp"
android:text="Hometools por UVA - 2015" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="57dp"
android:text="Tinta" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/button1"
android:layout_below="#+id/button1"
android:layout_marginTop="37dp"
android:text="Piso" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="BTU" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/button3"
android:layout_below="#+id/button3"
android:layout_marginTop="46dp"
android:text="Aquecedor" />
<Button
android:id="#+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView2"
android:layout_centerHorizontal="true"
android:layout_marginBottom="32dp"
android:text="Caixa d´água" />
</RelativeLayout>
Here is my logcat:
06-20 14:11:27.560: D/AndroidRuntime(824): Shutting down VM
06-20 14:11:27.560: W/dalvikvm(824): threadid=1: thread exiting with uncaught exception (group=0xb2a68ba8)
06-20 14:11:27.580: E/AndroidRuntime(824): FATAL EXCEPTION: main
06-20 14:11:27.580: E/AndroidRuntime(824): Process: com.example.hometools, PID: 824
06-20 14:11:27.580: E/AndroidRuntime(824): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.hometools/com.example.hometools.HometoolsActivity}: java.lang.NullPointerException
06-20 14:11:27.580: E/AndroidRuntime(824): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
06-20 14:11:27.580: E/AndroidRuntime(824): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
06-20 14:11:27.580: E/AndroidRuntime(824): at android.app.ActivityThread.access$800(ActivityThread.java:135)
06-20 14:11:27.580: E/AndroidRuntime(824): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
06-20 14:11:27.580: E/AndroidRuntime(824): at android.os.Handler.dispatchMessage(Handler.java:102)
06-20 14:11:27.580: E/AndroidRuntime(824): at android.os.Looper.loop(Looper.java:136)
06-20 14:11:27.580: E/AndroidRuntime(824): at android.app.ActivityThread.main(ActivityThread.java:5001)
06-20 14:11:27.580: E/AndroidRuntime(824): at java.lang.reflect.Method.invokeNative(Native Method)
06-20 14:11:27.580: E/AndroidRuntime(824): at java.lang.reflect.Method.invoke(Method.java:515)
06-20 14:11:27.580: E/AndroidRuntime(824): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
06-20 14:11:27.580: E/AndroidRuntime(824): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
06-20 14:11:27.580: E/AndroidRuntime(824): at dalvik.system.NativeStart.main(Native Method)
06-20 14:11:27.580: E/AndroidRuntime(824): Caused by: java.lang.NullPointerException
06-20 14:11:27.580: E/AndroidRuntime(824): at com.example.hometools.HometoolsActivity.controleCaixa(HometoolsActivity.java:294)
06-20 14:11:27.580: E/AndroidRuntime(824): at com.example.hometools.HometoolsActivity.controlePrincipal(HometoolsActivity.java:75)
06-20 14:11:27.580: E/AndroidRuntime(824): at com.example.hometools.HometoolsActivity.onCreate(HometoolsActivity.java:66)
06-20 14:11:27.580: E/AndroidRuntime(824): at android.app.Activity.performCreate(Activity.java:5231)
06-20 14:11:27.580: E/AndroidRuntime(824): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
06-20 14:11:27.580: E/AndroidRuntime(824): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
06-20 14:11:27.580: E/AndroidRuntime(824): ... 11 more
06-20 14:12:37.752: I/Process(824): Sending signal. PID: 824 SIG: 9
Your error is here, it's a simple typo:
public void controleCaixa(){
button1t5 = (Button) findViewById(R.id.button1t5);
button1t5.setOnClickListener (new OnClickListener() {...}
...
}
It should be R.id.button5 not R.id.button1t5:
public void controleCaixa(){
button5 = (Button) findViewById(R.id.button5);
button5.setOnClickListener (new OnClickListener() {...}
...
}
Looking at the log, it's clear:
Caused by: java.lang.NullPointerException 06-20 14:11:27.580:
E/AndroidRuntime(824): at
com.example.hometools.HometoolsActivity.controleCaixa(HometoolsActivity.java:294)
06-20 14:11:27.580: E/AndroidRuntime(824):

Skipped 49 frames! The application may be doing too much work on its main thread

I am inflating Views (not fragments) in my viewpager implementation. My main class extends Activity.
I face this error when I try to swipe screen from my app or
at com.example.app.CustomPagerAdapter.instantiateItem(CustomPagerAdapter.java:47)
and
01-04 16:44:35.5278614-8614/com.parsizabanan.app W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4195ee48)
01-04 16:44:35.5278614-8614/com.parsizabanan.app E/AndroidRuntime﹕ FatAL EXCEPTION: main
Process: com.parsizabanan.app, PID: 8614
android.view.InflateException: Binary XML file line #6: Error inflating class <unknown>
at android.view.LayoutInflater.createView(LayoutInflater.java:620)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInfl ater.java:56)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:669)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:694)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at com.parsizabanan.app.CustomPagerAdapter.instantiateItem(CustomPagerAdapter.java:47)
at android.support.v4.view.PagerAdapter.instantiateItem(PagerAdapter.java:110)
at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:837)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1021)
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:16574)
at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
at android.view.View.measure(View.java:16574)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5140)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:16574)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5140)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1406)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:697)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:590)
at android.view.View.measure(View.java:16574)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5140)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2421)
at android.view.View.measure(View.java:16574)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1955)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1151)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1333)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1038)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5890)
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:5118)
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:794)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:610)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.constructNative(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at android.view.LayoutInflater.createView(LayoutInflater.java:594)
at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInfl ater.java:56)
at android.view.LayoutInflater.onCreateView(LayoutInflater.java:669)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:694)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at com.parsizabanan.app.CustomPagerAdapter.instantiateItem(CustomPagerAdapter.java:47)
at android.support.v4.view.PagerAdapter.instantiateItem(PagerAdapter.java:110)
at android.support.v4.view.ViewPager.addNewItem(ViewPager.java:837)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1021)
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:16574)
at android.widget.RelativeLayout.measureChildHorizontal(Rel ativeLayout.java:719)
at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
at android.view.View.measure(View.java:16574)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5140)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at android.view.View.measure(View.java:16574)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5140)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1406)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:697)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:590)
at android.view.View.measure(View.java:16574)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5140)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2421)
at android.view.View.measure(View.java:16574)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1955)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1151)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1333)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1038)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5890)
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:5118)
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:794)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:610)
at dalvik.system.NativeStart.main(Native Method)
Caused by: 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.cre ateFromResourceStream(Drawable.java:840)
at android.content.res.Resources.loadDrawable(Resources.java:2150)
CustomPagerAdapter:
public class CustomPagerAdapter extends PagerAdapter {
public Object instantiateItem(View collection, int position) {
LayoutInflaterinflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLatER_SERVICE);
int resId = 0;
switch (position) {
case 0: {
resId = R.layout.lab;
break;
}
case 1: {
resId = R.layout.lab;
break;
}
case 2: {
resId = R.layout.etela;
break;
}
case 3: {
resId = R.layout.ticket;
break;
}
case 4: {
resId = R.layout.product;
break;
}
case 5: {
resId = R.layout.about;
break;
}
}
View view = inflater.inflate(resId, null);
((ViewPager) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveSt ate() {
return null;
}
#Override
public int getCount() {
return 6;
}
MyActivity:
public class MyActivity extends Activity {
ViewPager myPager = null;
ImageButton contact = null;
ImageButton about = null;
ImageButton lab = null;
ImageButton product = null;
ImageButton ticket = null;
ImageButton etela = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
CustomPagerAdapter adapter = new CustomPagerAdapter();
myPager = (ViewPager) findViewById(R.id.customviewpager);
myPager.setAdapter(adapter);
myPager.setCurrentItem(5);
myPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrolled(int i, flo at v, int i2) {
}
public void onPageSelected(int i) {
}
public void onPageScrollStateChanged(int i) {
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
switch (myPager.getCurrentItem()) {
case 0:
break;
case 1:
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
break;
}
}
});
t1.start();
}
});
}
and is it lab layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/lab1"/>
</LinearLayout>
Using large images could cause this error. Its highly recommended to reduce images sizes and then load them to ImageViews.
Also there is an other way to request android to give your application more memory by adding the following to the manifest . But this is not recommended. For more information look at here and here.
<application
...
android:largeHeap="true"
...
>
...
</application>

Using an intent to chose a specific layout from previous activity - layered

So what I have is a main Activity A_TheList_Activity, from here I move to the next Activity B_Target_Activity with an intent that I put in a specific layout file I created corresponding to the right button the user chose.
That works just fine, However when I try the exact same method with the next activity, the one receiving from the first that will be moving to the third and provide the specific layout corresponding to the button chosen (B_Target_Activity moving to C_Sub_Target_Activity) I receive a NullPointerException. The reason I want to know the specific layout is because I want to be able to identify and give instructions to all the buttons I will put in it.
I do the exact same thing and yet when i get to the second activity and try to go to the third I get a message saying my app has stopped working and it takes me back to the first Activity. Somebody PLEASE help. Also if you know a simpler way to do this that would be easy for a beginning programmer to understand that would be AWESOME TOO!
Here is my code
A__TheList_Activity:
public class A_TheList_Activity extends Activity {
public static String LIST_CHOICE_MESSAGE = "THE LIST";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a_the_list_layout);
Button Family_Button = (Button) findViewById(R.id.Family_Button);
Family_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent TargetIntent = new Intent(getApplicationContext(), B_Target_Activity.class);
TargetIntent.putExtra(LIST_CHOICE_MESSAGE, R.layout.target_family_layout);
startActivity(TargetIntent);
}
});
Button Friends_Button = (Button) findViewById(R.id.Friends_Button);
Friends_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), B_Target_Activity.class);
intent.putExtra(LIST_CHOICE_MESSAGE, R.layout.target_friends_layout);
startActivity(intent);
}
});
Button Love_Button = (Button) findViewById(R.id.Love_Button);
Love_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), B_Target_Activity.class);
intent.putExtra(LIST_CHOICE_MESSAGE, R.layout.target_love_layout);
startActivity(intent);
}
});
Button Culture_Button = (Button) findViewById(R.id.Culture_Button);
Culture_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), B_Target_Activity.class);
intent.putExtra(LIST_CHOICE_MESSAGE, R.layout.target_culture_layout);
startActivity(intent);
}
});
}
}
B_Target_Activity:
public class B_Target_Activity extends Activity {
public static String TARGET_CHOICE_TO_SUB_MESSAGE = "Une Target";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle intent = getIntent().getExtras();
Integer layout = intent.getInt(A_TheList_Activity.LIST_CHOICE_MESSAGE, 0);
setContentView(layout);
LayoutChoice(layout);
}
public void LayoutChoice(Integer i){
if(i.equals(R.layout.target_family_layout)){
Button FamilyTargetButton = (Button) findViewById(R.id.FamilyTargetButton);
FamilyTargetButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent SubIntent = new Intent(B_Target_Activity.this, C_Sub_Target_Activity.class);
SubIntent.putExtra(TARGET_CHOICE_TO_SUB_MESSAGE, R.layout.sub_family_layout);
startActivity(SubIntent);
}
});
}else if(i.equals(R.layout.target_friends_layout)){
Button FriendsTargetButton = (Button) findViewById(R.id.FriendsTargetButton);
FriendsTargetButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent SubIntent = new Intent(B_Target_Activity.this, C_Sub_Target_Activity.class);
SubIntent.putExtra(TARGET_CHOICE_TO_SUB_MESSAGE, R.layout.sub_friends_layout);
startActivity(SubIntent);
}
});
}else if(i.equals(R.layout.target_love_layout)){
Button LoveTargetButton = (Button) findViewById(R.id.LoveTargetButton);
LoveTargetButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent SubIntent = new Intent(B_Target_Activity.this, C_Sub_Target_Activity.class);
SubIntent.putExtra(TARGET_CHOICE_TO_SUB_MESSAGE, R.layout.sub_love_layout);
startActivity(SubIntent);
}
});
}else if(i.equals(R.layout.target_culture_layout)){
Button CultureTargetButton = (Button) findViewById(R.id.CultureTargetButton);
CultureTargetButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent SubIntent = new Intent(B_Target_Activity.this, C_Sub_Target_Activity.class);
SubIntent.putExtra(TARGET_CHOICE_TO_SUB_MESSAGE, R.layout.sub_culture_layout);
startActivity(SubIntent);
}
});
}
}
}
C_Sub_Target_Activity, where the NullPointerException happens:
public class C_Sub_Target_Activity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle intent = getIntent().getExtras();
int layout = intent.getInt(A_TheList_Activity.LIST_CHOICE_MESSAGE, 0);
setContentView(layout);
}
}
Here is my LogCat, Thank you so Much again!!!
07-09 00:02:08.324: D/(1787): HostConnection::get() New Host Connection established 0xb8a7f688, tid 1787
07-09 00:02:08.754: W/EGL_emulation(1787): eglSurfaceAttrib not implemented
07-09 00:02:08.804: D/OpenGLRenderer(1787): Enabling debug mode 0
07-09 00:02:14.394: W/EGL_emulation(1787): eglSurfaceAttrib not implemented
07-09 00:02:17.074: W/ResourceType(1787): No package identifier when getting value for resource number 0x00000000
07-09 00:02:17.074: D/AndroidRuntime(1787): Shutting down VM
07-09 00:02:17.074: W/dalvikvm(1787): threadid=1: thread exiting with uncaught exception (group=0xb3aa3ba8)
07-09 00:02:17.184: E/AndroidRuntime(1787): FATAL EXCEPTION: main
07-09 00:02:17.184: E/AndroidRuntime(1787): Process: com.example.testinttesting, PID: 1787
07-09 00:02:17.184: E/AndroidRuntime(1787): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.testinttesting/com.example.testinttesting.C_Sub_Target_Activity}: android.content.res.Resources$NotFoundException: Resource ID #0x0
07-09 00:02:17.184: E/AndroidRuntime(1787): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
07-09 00:02:17.184: E/AndroidRuntime(1787): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
07-09 00:02:17.184: E/AndroidRuntime(1787): at android.app.ActivityThread.access$800(ActivityThread.java:135)
07-09 00:02:17.184: E/AndroidRuntime(1787): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
07-09 00:02:17.184: E/AndroidRuntime(1787): at android.os.Handler.dispatchMessage(Handler.java:102)
07-09 00:02:17.184: E/AndroidRuntime(1787): at android.os.Looper.loop(Looper.java:136)
07-09 00:02:17.184: E/AndroidRuntime(1787): at android.app.ActivityThread.main(ActivityThread.java:5017)
07-09 00:02:17.184: E/AndroidRuntime(1787): at java.lang.reflect.Method.invokeNative(Native Method)
07-09 00:02:17.184: E/AndroidRuntime(1787): at java.lang.reflect.Method.invoke(Method.java:515)
07-09 00:02:17.184: E/AndroidRuntime(1787): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
07-09 00:02:17.184: E/AndroidRuntime(1787): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
07-09 00:02:17.184: E/AndroidRuntime(1787): at dalvik.system.NativeStart.main(Native Method)
07-09 00:02:17.184: E/AndroidRuntime(1787): Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x0
07-09 00:02:17.184: E/AndroidRuntime(1787): at android.content.res.Resources.getValue(Resources.java:1123)
07-09 00:02:17.184: E/AndroidRuntime(1787): at android.content.res.Resources.loadXmlResourceParser(Resources.java:2309)
07-09 00:02:17.184: E/AndroidRuntime(1787): at android.content.res.Resources.getLayout(Resources.java:939)
07-09 00:02:17.184: E/AndroidRuntime(1787): at android.view.LayoutInflater.inflate(LayoutInflater.java:395)
07-09 00:02:17.184: E/AndroidRuntime(1787): at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
07-09 00:02:17.184: E/AndroidRuntime(1787): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:290)
07-09 00:02:17.184: E/AndroidRuntime(1787): at android.app.Activity.setContentView(Activity.java:1929)
07-09 00:02:17.184: E/AndroidRuntime(1787): at com.example.testinttesting.C_Sub_Target_Activity.onCreate(C_Sub_Target_Activity.java:18)
07-09 00:02:17.184: E/AndroidRuntime(1787): at android.app.Activity.performCreate(Activity.java:5231)
07-09 00:02:17.184: E/AndroidRuntime(1787): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
07-09 00:02:17.184: E/AndroidRuntime(1787): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
07-09 00:02:17.184: E/AndroidRuntime(1787): ... 11 more
07-09 00:02:21.024: D/(1812): HostConnection::get() New Host Connection established 0xb8a7f770, tid 1812
07-09 00:02:21.584: W/EGL_emulation(1812): eglSurfaceAttrib not implemented
07-09 00:02:21.624: D/OpenGLRenderer(1812): Enabling debug mode 0
Use B_Target_Activity.TARGET_CHOICE_TO_SUB_MESSAGE as key in C_Sub_Target_Activity because you are passing layout id from Activity B_Target_Activity instead of from A_TheList_Activity:
if(intent !=null){
if(intent.containsKey(B_Target_Activity.TARGET_CHOICE_TO_SUB_MESSAGE)){
int layout = intent.getInt(B_Target_Activity.TARGET_CHOICE_TO_SUB_MESSAGE, 0);
setContentView(layout);
}
}
You access wrong key try to replace this code :
int layout = intent.getInt(A_TheList_Activity.LIST_CHOICE_MESSAGE, 0);
With this code :
int layout = intent.getInt(A_TheList_Activity.TARGET_CHOICE_TO_SUB_MESSAGE, 0);

Button click causing null pointer

Every time I click on the button, the app crashes. I have trouble finding the bug, but I'm sure it has to do something with either the onClickListener, or the onClick function.
Note: I'm using Parse API for some back end stuff. But I highly doubt it has anything to do with any of the Parse stuff.
Here's what my code looks like:
public class SignUpActivity extends Activity {
protected EditText mUserName;
protected EditText mPassword;
protected EditText mEmail;
protected Button mSignUpButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_sign_up);
mUserName = (EditText) findViewById(R.id.usernameField);
mPassword = (EditText) findViewById(R.id.passwordField);
mEmail = (EditText) findViewById(R.id.emailField);
mSignUpButton = (Button) findViewById(R.id.signupButton);
mSignUpButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = mUserName.getText().toString();
String password = mPassword.getText().toString();
String email = mEmail.getText().toString();
username = username.trim();
password = password.trim();
email = email.trim();
if(username.isEmpty() || password.isEmpty() || email.isEmpty()){
AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
builder.setMessage(R.string.signup_error_message)
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
else{
setProgressBarIndeterminateVisibility(true);
ParseUser newUser = new ParseUser();
newUser.setUsername(username);
newUser.setPassword(password);
newUser.setEmail(email);
newUser.signUpInBackground(new SignUpCallback() {
#Override
public void done(ParseException e) {
setProgressBarIndeterminateVisibility(false);
if(e == null){
// success
Intent intent = new Intent(SignUpActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
else{
AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
builder.setMessage(e.getMessage())
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
});
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.sign_up, menu);
return true;
}
}
Here's my Log Cat:
04-14 14:19:05.881: E/AndroidRuntime(1156): FATAL EXCEPTION: main 04-14 14:19:05.881:
E/AndroidRuntime(1156): Process: com.ebad.ribbit, PID: 1156 04-14 14:19:05.881:
E/AndroidRuntime(1156): java.lang.NullPointerException 04-14 14:19:05.881:
E/AndroidRuntime(1156): at com.ebad.ribbit.SignUpActivity$1.onClick(SignUpActivity.java:40) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at android.view.View.performClick(View.java:4438) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at android.view.View$PerformClick.run(View.java:18422) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at android.os.Handler.handleCallback(Handler.java:733) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at android.os.Handler.dispatchMessage(Handler.java:95) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at android.os.Looper.loop(Looper.java:136) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at android.app.ActivityThread.main(ActivityThread.java:5017) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at java.lang.reflect.Method.invokeNative(Native Method) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at java.lang.reflect.Method.invoke(Method.java:515) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 04-14 14:19:05.881:
E/AndroidRuntime(1156): at dalvik.system.NativeStart.main(Native Method)
EDIT:
As requested, here is line 40:
String username = mUserName.getText().toString();
EDIT 2:
Here is the log cat after adding Log.i(TAG, mUserName == null ? "mUserName is null" : mUserName.getText() == null ? "mUserName.getText() is null" : "nothing is null"); :
04-14 15:21:47.955: E/AndroidRuntime(1318): FATAL EXCEPTION: main
04-14 15:21:47.955: E/AndroidRuntime(1318): Process: com.ebad.ribbit, PID: 1318
04-14 15:21:47.955: E/AndroidRuntime(1318): java.lang.NullPointerException
04-14 15:21:47.955: E/AndroidRuntime(1318): at com.ebad.ribbit.SignUpActivity$1.onClick(SignUpActivity.java:43)
04-14 15:21:47.955: E/AndroidRuntime(1318): at android.view.View.performClick(View.java:4438)
04-14 15:21:47.955: E/AndroidRuntime(1318): at android.view.View$PerformClick.run(View.java:18422)
04-14 15:21:47.955: E/AndroidRuntime(1318): at android.os.Handler.handleCallback(Handler.java:733)
04-14 15:21:47.955: E/AndroidRuntime(1318): at android.os.Handler.dispatchMessage(Handler.java:95)
04-14 15:21:47.955: E/AndroidRuntime(1318): at android.os.Looper.loop(Looper.java:136)
04-14 15:21:47.955: E/AndroidRuntime(1318): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-14 15:21:47.955: E/AndroidRuntime(1318): at java.lang.reflect.Method.invokeNative(Native Method)
04-14 15:21:47.955: E/AndroidRuntime(1318): at java.lang.reflect.Method.invoke(Method.java:515)
04-14 15:21:47.955: E/AndroidRuntime(1318): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-14 15:21:47.955: E/AndroidRuntime(1318): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-14 15:21:47.955: E/AndroidRuntime(1318): at dalvik.system.NativeStart.main(Native Method)
EDIT 3:
Upon Request, here is my activity_sign_up.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".SignUpActivity" >
<EditText
android:id="#+id/userNameField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:hint="#string/username_hint"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/passwordField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/userNameField"
android:ems="10"
android:hint="#string/password_hint"
android:inputType="textPassword" />
<EditText
android:id="#+id/emailField"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/passwordField"
android:ems="10"
android:hint="#string/email_hint"
android:inputType="textEmailAddress" />
<Button
android:id="#+id/signupButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/emailField"
android:layout_below="#+id/emailField"
android:layout_marginTop="50dp"
android:text="#string/sign_up_button_label" />
</RelativeLayout>
Do this please:
#Override
public void onClick(View v) {
if(mUserName != null && mPassword != null && mEmail != null && mUserName.getText() != null && mPassword.getText() != null && mEmail.getText() != null)
{
Your original code here.
}
}
Update:
Typo
mUserName = (EditText) findViewById(R.id.usernameField); should be userNameField?
<EditText android:id="#+id/userNameField" ...
If mUsername is null, calling getText() on it will cause a NullPointerException. You should check that it's not null before doing this. Try changing to the following:
if(mUserName == null || mPassword == null || mEmail == null){
AlertDialog.Builder builder = new AlertDialog.Builder(SignUpActivity.this);
builder.setMessage(R.string.signup_error_message)
.setTitle(R.string.signup_error_title)
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
String username = mUserName.getText().toString();
String password = mPassword.getText().toString();
String email = mEmail.getText().toString();
username = username.trim();
password = password.trim();
email = email.trim();
Try
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
https://developer.android.com/guide/topics/ui/dialogs.html
Also make sure that SignUpActivity is declared in the app manifest. I guess make sure that all activities are set up in the manifest.
EDIT 1
If line 40 is the issue, then
mUserName is null
or
mUserName.getText() is null. So create a couple checks before hand and also add some debug logs to just verify that they are not null.
Make sure that R.layout.activity_sign_up has usernameField as an id. Also make sure in any other app/res/layout folders (ie layout-v14), that all R.layout.activity_sign_up has the edittext as well.
If this errors occurred in your line 40, that means your are getting null from your EditText.
Try it in every place you are getting a string. At least it will save you from getting null pointer exception from EditText.
String username = String.valueOf(mUserName.getText());
String password = String.valueOf(mPassword.getText());
String email = String.valueOf(mEmail.getText());

Runtime Exception unable to start MainActivity

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

Categories