Android App crash: FATAL EXCEPTION: main - java

I wrote Android QuizApp which randomly generates questions for users and then displays the result. When I tried to implement user interface where a user would enter the number and difficulty of questions, application started to crash and give me fatal exceptions. I have 4 classes:
package com.example.quizapp;
import java.util.Random;
public class Quiz {
private int difficulty;
private int numberOfQuestions;
private Question[] questions;
public Quiz(String difficulty, int numberOfQuestions) {
setDifficulty(difficulty);
this.numberOfQuestions = numberOfQuestions;
this.questions = new Question[this.numberOfQuestions];
for (int i = 0; i < this.numberOfQuestions; i++) {
this.questions[i] = new Question(this.difficulty);
}
}
public void setDifficulty(String difficulty) {
if (difficulty == "easy") {
this.difficulty = 1;
} else if (difficulty == "medium"){
this.difficulty = 2;
} else if (difficulty == "hard"){
this.difficulty = 3;
} else {
this.difficulty = -1;
}
}
public String getDifficulty() {
switch (difficulty) {
case 1:
return "easy";
case 2:
return "medium";
case 3:
return "hard";
default:
return "Difficulty not set correctly";
}
}
public Question getQuestionInstance(int number) {
return this.questions[number];
}
public String getQuestion(int number) {
return this.questions[number].QUESTION;
}
public int getOptionA(int number) {
return this.questions[number].OPTA;
}
public int getOptionB(int number) {
return this.questions[number].OPTB;
}
public int getOptionC(int number) {
return this.questions[number].OPTC;
}
public int getAnswer(int number) {
return this.questions[number].ANSWER;
}
class Question {
private int firstNumber;
private int secondNumber;
private char sign;
private String QUESTION;
private int OPTA;
private int OPTB;
private int OPTC;
private int ANSWER;
private int difficulty;
private Random rand;
public Question(int difficulty) {
this.difficulty = difficulty;
this.rand = new Random();
this.firstNumber = getRandomNumber();
this.secondNumber = getRandomNumber();
this.sign = getRandomSign();
this.ANSWER = calculateAnswer();
initializeOptions();
this.QUESTION = this.firstNumber + " " + this.sign + " " + this.secondNumber + " = ";
}
public String getQuestion() {
return this.QUESTION;
}
public int getOptionA() {
return this.OPTA;
}
public int getOptionB() {
return this.OPTB;
}
public int getOptionC() {
return this.OPTC;
}
public int getAnswer() {
return this.ANSWER;
}
private void initializeOptions() {
int number = this.rand.nextInt(3) + 1;
switch (number) {
case 1:
this.OPTA = this.ANSWER;
this.OPTB = (int) Math.floor(this.ANSWER - this.ANSWER / 100.0 * (this.rand.nextInt(81) + 20));
this.OPTC = (int) Math.floor(this.ANSWER + this.ANSWER / 100.0 * (this.rand.nextInt(81) + 20));
break;
case 2:
this.OPTA = (int) Math.floor(this.ANSWER - this.ANSWER / 100.0 * (this.rand.nextInt(81) + 20));
this.OPTB = this.ANSWER;
this.OPTC = (int) Math.floor(this.ANSWER + this.ANSWER / 100.0 * (this.rand.nextInt(81) + 20));
break;
case 3:
this.OPTA = (int) Math.floor(this.ANSWER - this.ANSWER / 100.0 * (this.rand.nextInt(81) + 20));
this.OPTB = (int) Math.floor(this.ANSWER + this.ANSWER / 100.0 * (this.rand.nextInt(81) + 20));
this.OPTC = this.ANSWER;
break;
}
}
private int calculateAnswer() {
int answer = 0;
switch (this.sign) {
case '+':
answer = this.firstNumber + this.secondNumber;
break;
case '-':
answer = this.firstNumber - this.secondNumber;
break;
case '*':
answer = this.firstNumber * this.secondNumber;
break;
case '/':
answer = this.firstNumber / this.secondNumber;
break;
}
return answer;
}
private int getRandomNumber() {
int number;
if (this.difficulty == 1) {
//number = 1 + Math.random()*100;
number = this.rand.nextInt(100) + 1;
} else if (this.difficulty == 2) {
//number = 1 + Math.random()*1000;
number = this.rand.nextInt(1000) + 1;
} else {
//number = 1 + Math.random()*1000;
number = this.rand.nextInt(1000) + 1;
}
return number;
}
private char getRandomSign() {
int number;
char sign;
//easy
if (this.difficulty == 1) {
number = this.rand.nextInt(2) + 1;
sign = convertNumberToSign(number);
//medium
} else if (this.difficulty == 2) {
if (this.firstNumber > 10 && this.secondNumber > 10) {
number = this.rand.nextInt(2) + 1;
sign = convertNumberToSign(number);
} else {
number = this.rand.nextInt(3) + 1;
sign = convertNumberToSign(number);
}
//hard
} else {
if (this.firstNumber / this.secondNumber == (int) (this.firstNumber / this.secondNumber)) {
number = this.rand.nextInt(4) + 1;
sign = convertNumberToSign(number);
} else {
number = this.rand.nextInt(3) + 1;
sign = convertNumberToSign(number);
}
}
return sign;
}
private char convertNumberToSign(int number) {
if (number == 1) {
return '+';
} else if (number == 2) {
return '-';
} else if (number == 3) {
return '*';
} else {
return '/';
}
}
}
}
package com.example.quizapp;
import com.example.quizapp.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class QuizActivity extends Activity
{
Quiz quiz;
RadioButton rb1, rb2, rb3, rb4, rb5, rb6;
Button buttonOK;
String ans;
int num = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ui);
rb1=(RadioButton)findViewById(R.id.radio3);
rb2=(RadioButton)findViewById(R.id.radio4);
rb3=(RadioButton)findViewById(R.id.radio5);
rb4=(RadioButton)findViewById(R.id.radio6);
rb5=(RadioButton)findViewById(R.id.radio7);
rb6=(RadioButton)findViewById(R.id.radio8);
buttonOK=(Button)findViewById(R.id.button2);
buttonOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup group2=(RadioGroup)findViewById(R.id.radioGroup3);
RadioButton answer2=(RadioButton)findViewById(group2.getCheckedRadioButtonId());
if (answer2.equals(rb4))
{
num = 5;
}
else if (answer2.equals(rb5))
{
num = 10;
}
else
{
num = 15;
}
RadioGroup group1=(RadioGroup)findViewById(R.id.radioGroup2);
RadioButton answer1=(RadioButton)findViewById(group1.getCheckedRadioButtonId());
if (answer1.equals(rb1))
{
ans = "easy";
}
else if (answer1.equals(rb2))
{
ans = "medium";
}
else
{
ans = "hard";
}
}
});
Intent intent = new Intent(QuizActivity.this, QuestActivity.class);
intent.putExtra("answer", ans);
intent.putExtra("question", num);
QuizActivity.this.startActivity(intent);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_ui, menu);
return true;
}
}
package com.example.quizapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class QuestActivity extends Activity
{
Quiz quiz;
int score = 0;
int qid = 0;
Quiz.Question currentQuest;
TextView textQuestion;
RadioButton rba, rbb, rbc;
Button buttonNext;
String answer = null;
int numOfQuestion = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
Intent intent= getIntent();
if (intent != null)
{
answer=intent.getStringExtra("answer");
numOfQuestion=intent.getIntExtra("question", 0);
}
quiz= new Quiz(answer,numOfQuestion);
currentQuest=quiz.getQuestionInstance(qid);
textQuestion=(TextView)findViewById(R.id.textView1);
rba=(RadioButton)findViewById(R.id.radio0);
rbb=(RadioButton)findViewById(R.id.radio1);
rbc=(RadioButton)findViewById(R.id.radio2);
buttonNext=(Button)findViewById(R.id.button1);
setQuestionView();
buttonNext.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
RadioGroup group=(RadioGroup)findViewById(R.id.radioGroup1);
RadioButton answer=(RadioButton)findViewById(group.getCheckedRadioButtonId());
Log.d("yourans", currentQuest.getAnswer() + " " + answer.getText());
if(Integer.toString(currentQuest.getAnswer()).equals(answer.getText()) )
{
score++;
Log.d("score", "Your score" + score);
}
if(qid<numOfQuestion)
{
currentQuest=quiz.getQuestionInstance(qid);
setQuestionView();
}else
{
Intent intent = new Intent(QuestActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score);
intent.putExtras(b);
startActivity(intent);
finish();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_quiz, menu);
return true;
}
private void setQuestionView()
{
textQuestion.setText(currentQuest.getQuestion());
rba.setText(Integer.toString(currentQuest.getOptionA()));
rbb.setText(Integer.toString(currentQuest.getOptionB()));
rbc.setText(Integer.toString(currentQuest.getOptionC()));
qid++;
}
}
package com.example.quizapp;
import com.example.quizapp.R;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.RatingBar;
import android.widget.TextView;
public class ResultActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
//access rating bar
RatingBar rbar=(RatingBar)findViewById(R.id.ratingBar1);
rbar.setNumStars(5);
rbar.setStepSize(0.5f);
TextView t=(TextView)findViewById(R.id.textResult);
//get and display the score
Bundle b = getIntent().getExtras();
int score= b.getInt("score");
rbar.setRating(score);
switch (score)
{
case 1:
case 2: t.setText("Better Luck Next Time!");
break;
case 3:
case 4:t.setText("Quite average");
break;
case 5:t.setText("Congratulations !");
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_result, menu);
return true;
}
}
Edited: I added AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.quizapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.quizapp.QuizActivity"
android:label="#string/quiz_app" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.quizapp.QuestActivity"
android:label="#string/title_activity_quiz" >
</activity>
<activity
android:name="com.example.quizapp.ResultActivity"
android:label="#string/title_activity_result" >
</activity>
</application>
</manifest>
Edited: Updated application as suggested, this error pops up and app crashes:
10-23 10:10:32.368: E/AndroidRuntime(827): FATAL EXCEPTION: main
10-23 10:10:32.368: E/AndroidRuntime(827): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.quizapp/com.example.quizapp.QuestActivity}: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.os.Handler.dispatchMessage(Handler.java:99)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.os.Looper.loop(Looper.java:137)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.ActivityThread.main(ActivityThread.java:5103)
10-23 10:10:32.368: E/AndroidRuntime(827): at java.lang.reflect.Method.invokeNative(Native Method)
10-23 10:10:32.368: E/AndroidRuntime(827): at java.lang.reflect.Method.invoke(Method.java:525)
10-23 10:10:32.368: E/AndroidRuntime(827): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-23 10:10:32.368: E/AndroidRuntime(827): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-23 10:10:32.368: E/AndroidRuntime(827): at dalvik.system.NativeStart.main(Native Method)
10-23 10:10:32.368: E/AndroidRuntime(827): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
10-23 10:10:32.368: E/AndroidRuntime(827): at com.example.quizapp.Quiz.getQuestionInstance(Quiz.java:45)
10-23 10:10:32.368: E/AndroidRuntime(827): at com.example.quizapp.QuestActivity.onCreate(QuestActivity.java:52)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.Activity.performCreate(Activity.java:5133)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-23 10:10:32.368: E/AndroidRuntime(827): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
10-23 10:10:32.368: E/AndroidRuntime(827): ... 11 more

check this in manifest:
android:name="com.example.quizapp.QuizApp"
Have you this activity "QuizApp"?
change in manifest to:
android:name="com.example.quizapp.QuizActivity"
HTH.

You told Android that you have an Activity named QuizApp as your Main Activity, by saying
<activity
android:name="com.example.quizapp.QuizApp"
android:label="#string/quiz_app" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
but you never implemented it. Android looks for that activity in the package, com.example.quizapp, but it fails to find it, as we can see from the ClassNotFoundException in the LogCat messages,
10-21 06:31:26.907: E/AndroidRuntime(816): ... java.lang.ClassNotFoundException: Didn't find class "com.example.quizapp.QuizApp"...
You must implement your QuizApp Activity.

Its look like you have package name mismatch error in Manifest file. Correct it as
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.quizapp"
...
</manifest>
And don't forget, you can specify the fully qualified name for each Activity
i.e.
<activity
android:name="com.example.quizapp.Activity_name"
...>
</activity>
Edit As per Requirement
package com.example.quizapp;
import com.example.quizapp.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
public class QuizActivity extends Activity
{
Quiz quiz;
RadioButton rb1, rb2, rb3, rb4, rb5, rb6;
Button buttonOK;
String ans;
int num = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ui);
rb1=(RadioButton)findViewById(R.id.radio3);
rb2=(RadioButton)findViewById(R.id.radio4);
rb3=(RadioButton)findViewById(R.id.radio5);
rb4=(RadioButton)findViewById(R.id.radio6);
rb5=(RadioButton)findViewById(R.id.radio7);
rb6=(RadioButton)findViewById(R.id.radio8);
buttonOK=(Button)findViewById(R.id.button2);
buttonOK.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup group2=(RadioGroup)findViewById(R.id.radioGroup3);
RadioButton answer2=(RadioButton)findViewById(group2.getCheckedRadioButtonId());
if (answer2.equals(rb4))
{
num = 5;
}
else if (answer2.equals(rb5))
{
num = 10;
}
else
{
num = 15;
}
RadioGroup group1=(RadioGroup)findViewById(R.id.radioGroup2);
RadioButton answer1=(RadioButton)findViewById(group1.getCheckedRadioButtonId());
if (answer1.equals(rb1))
{
ans = "easy";
}
else if (answer1.equals(rb2))
{
ans = "medium";
}
else
{
ans = "hard";
}
}
});
//*********Edit
//Intent intent = new Intent(QuizActivity.this, QuestActivity.class);
//QuizActivity.this.startActivity(intent);
//finish();
Intent intent = new Intent(QuizActivity.this, QuestActivity.class);
intent.putExtra("answer", ans);
intent.putExtra("question", num);
QuizActivity.this.startActivity(intent);
finish();
//*******Edit
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_ui, menu);
return true;
}
}
Here Next Activity
package com.example.quizapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
public class QuestActivity extends Activity
{
Quiz quiz;
int score = 0;
int qid = 0;
Quiz.Question currentQuest;
TextView textQuestion;
RadioButton rba, rbb, rbc;
Button buttonNext;
QuizActivity qa = new QuizActivity();
String ans = qa.ans;
int num = qa.num;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
//*********Edit
Intent intent= getActivity().getIntent();
String answer=intent.getStringExtra("answer");
int numOfQuestion=intent.getIntExtra("question", 0);
//quiz= new Quiz(ans, num);
quiz= new Quiz(answer,numOfQuestion);
//*******
currentQuest=quiz.getQuestionInstance(qid);
textQuestion=(TextView)findViewById(R.id.textView1);
rba=(RadioButton)findViewById(R.id.radio0);
rbb=(RadioButton)findViewById(R.id.radio1);
rbc=(RadioButton)findViewById(R.id.radio2);
buttonNext=(Button)findViewById(R.id.button1);
setQuestionView();
buttonNext.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
RadioGroup group=(RadioGroup)findViewById(R.id.radioGroup1);
RadioButton answer=(RadioButton)findViewById(group.getCheckedRadioButtonId());
Log.d("yourans", currentQuest.getAnswer() + " " + answer.getText());
if(Integer.toString(currentQuest.getAnswer()).equals(answer.getText()) )
{
score++;
Log.d("score", "Your score" + score);
}
if(qid<num)
{
currentQuest=quiz.getQuestionInstance(qid);
setQuestionView();
}else
{
Intent intent = new Intent(QuestActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score);
intent.putExtras(b);
startActivity(intent);
finish();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_quiz, menu);
return true;
}
private void setQuestionView()
{
textQuestion.setText(currentQuest.getQuestion());
rba.setText(Integer.toString(currentQuest.getOptionA()));
rbb.setText(Integer.toString(currentQuest.getOptionB()));
rbc.setText(Integer.toString(currentQuest.getOptionC()));
qid++;
}
}

Related

Fragment not attached to a context (Using NavigationView)

This is my code
package com.packages.digifarm.ui.dashboard;
import android.content.Intent;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.cardview.widget.CardView;
import androidx.fragment.app.Fragment;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.packages.digifarm.KelembabanTanahAnalisisActivity;
import com.packages.digifarm.KelembabanUdaraAnalisisActivity;
import com.packages.digifarm.LevelKetinggianAirAnalisisActivity;
import com.packages.digifarm.R;
import com.packages.digifarm.SuhuAnalisisActivity;
public class DashboardFragment extends Fragment {
TextView tv_water_level_value, tv_temperature_value, tv_moisture_value, tv_humidity_value;
TextView tv_water_level_stats, tv_temperature_stats, tv_moisture_stats, tv_humidity_stats, tv_weather_stats;
ImageView ic_water, ic_weather_stats;
TextView tv_btn_show_detail_water_level, tv_btn_show_detail_soil_moisture, tv_btn_show_detail_temperature, tv_btn_show_detail_humidity;
CardView water_indicator;
ViewGroup.LayoutParams layoutParams;
DatabaseReference Reference;
String water_level_value, temperature_value, moisture_value, humidity_value, light_value;
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
tv_water_level_value = view.findViewById(R.id.tv_water_level_value);
tv_temperature_value = view.findViewById(R.id.tv_temperature_value);
tv_moisture_value = view.findViewById(R.id.tv_moisture_value);
tv_humidity_value = view.findViewById(R.id.tv_humidity_value);
tv_water_level_stats = view.findViewById(R.id.tv_water_level_stats);
tv_temperature_stats = view.findViewById(R.id.tv_temperature_stats);
tv_moisture_stats = view.findViewById(R.id.tv_moisture_stats);
tv_humidity_stats = view.findViewById(R.id.tv_humidity_stats);
tv_weather_stats = view.findViewById(R.id.tv_weather_stats);
water_indicator = view.findViewById(R.id.water_indicator);
ic_water = view.findViewById(R.id.ic_water);
ic_weather_stats = view.findViewById(R.id.ic_weather_stats);
Reference = FirebaseDatabase.getInstance().getReference("Current Data");
Reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
water_level_value = snapshot.child("Level Ketinggian Air").getValue().toString();
temperature_value = snapshot.child("Suhu").getValue().toString();
moisture_value = snapshot.child("Kelembaban Tanah").getValue().toString();
humidity_value = snapshot.child("Kelembaban Udara").getValue().toString();
light_value = snapshot.child("Cahaya").getValue().toString();
tv_water_level_value.setText(water_level_value + "%");
tv_temperature_value.setText(temperature_value + "°C");
tv_moisture_value.setText(moisture_value + "%");
tv_humidity_value.setText(humidity_value + "%");
layoutParams = (ViewGroup.LayoutParams)water_indicator.getLayoutParams();
layoutParams.height = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, Integer.parseInt(water_level_value), getResources().getDisplayMetrics()));
water_indicator.setLayoutParams(layoutParams);
if(Integer.parseInt(water_level_value) < 30){
tv_water_level_value.setTextColor(getResources().getColor(R.color.red_danger));
tv_water_level_stats.setText("Tersisa Sedikit");
tv_water_level_stats.setTextColor(getResources().getColor(R.color.red_danger));
water_indicator.setCardBackgroundColor(getResources().getColor(R.color.red_danger));
ic_water.setImageResource(R.drawable.ic_water_red);
}
else if(Integer.parseInt(water_level_value) >= 30 && Integer.parseInt(water_level_value) <= 50){
tv_water_level_value.setTextColor(getResources().getColor(R.color.yellow_warning));
tv_water_level_stats.setText("Cukup Banyak");
tv_water_level_stats.setTextColor(getResources().getColor(R.color.yellow_warning));
water_indicator.setCardBackgroundColor(getResources().getColor(R.color.yellow_warning));
ic_water.setImageResource(R.drawable.ic_water_yellow);
}
else if(Integer.parseInt(water_level_value) > 50 && Integer.parseInt(water_level_value) <= 75){
tv_water_level_value.setTextColor(getResources().getColor(R.color.teal_200));
tv_water_level_stats.setText("Lumayan Banyak");
tv_water_level_stats.setTextColor(getResources().getColor(R.color.teal_200));
water_indicator.setCardBackgroundColor(getResources().getColor(R.color.teal_200));
ic_water.setImageResource(R.drawable.ic_water_blue);
}
else if(Integer.parseInt(water_level_value) > 75){
tv_water_level_value.setTextColor(getResources().getColor(R.color.teal_200));
tv_water_level_stats.setText("Lumayan Banyak");
tv_water_level_stats.setTextColor(getResources().getColor(R.color.teal_200));
water_indicator.setCardBackgroundColor(getResources().getColor(R.color.teal_200));
ic_water.setImageResource(R.drawable.ic_water_blue);
}
if(Integer.parseInt(temperature_value) < 26){
tv_temperature_value.setTextColor(getResources().getColor(R.color.teal_200));
tv_temperature_stats.setText("Dingin");
tv_temperature_stats.setTextColor(getResources().getColor(R.color.teal_200));
}
else if(Integer.parseInt(temperature_value) >= 26 && Integer.parseInt(temperature_value) <= 34){
tv_temperature_value.setTextColor(getResources().getColor(R.color.secondary_green));
tv_temperature_stats.setText("Normal");
tv_temperature_stats.setTextColor(getResources().getColor(R.color.secondary_green));
}
else if(Integer.parseInt(temperature_value) > 34){
tv_temperature_value.setTextColor(getResources().getColor(R.color.red_danger));
tv_temperature_stats.setText("Panas");
tv_temperature_stats.setTextColor(getResources().getColor(R.color.red_danger));
}
if(Integer.parseInt(humidity_value) < 20){
tv_humidity_value.setTextColor(getResources().getColor(R.color.red_danger));
tv_humidity_stats.setText("Kering");
tv_humidity_stats.setTextColor(getResources().getColor(R.color.red_danger));
}
else if(Integer.parseInt(humidity_value) >= 20 && Integer.parseInt(humidity_value) <= 40){
tv_humidity_value.setTextColor(getResources().getColor(R.color.yellow_warning));
tv_humidity_stats.setText("Kering");
tv_humidity_stats.setTextColor(getResources().getColor(R.color.yellow_warning));
}
else if(Integer.parseInt(humidity_value) > 40 && Integer.parseInt(humidity_value) <= 70){
tv_humidity_value.setTextColor(getResources().getColor(R.color.secondary_green));
tv_humidity_stats.setText("Normal");
tv_humidity_stats.setTextColor(getResources().getColor(R.color.secondary_green));
}
else if(Integer.parseInt(humidity_value) > 70){
tv_humidity_value.setTextColor(getResources().getColor(R.color.teal_200));
tv_humidity_stats.setText("Lembab");
tv_humidity_stats.setTextColor(getResources().getColor(R.color.teal_200));
}
if(Integer.parseInt(moisture_value) < 20){
tv_moisture_value.setTextColor(getResources().getColor(R.color.red_danger));
tv_moisture_stats.setText("Kering");
tv_moisture_stats.setTextColor(getResources().getColor(R.color.red_danger));
}
else if(Integer.parseInt(moisture_value) >= 20 && Integer.parseInt(moisture_value) <= 40){
tv_moisture_value.setTextColor(getResources().getColor(R.color.yellow_warning));
tv_moisture_stats.setText("Kering");
tv_moisture_stats.setTextColor(getResources().getColor(R.color.yellow_warning));
}
else if(Integer.parseInt(moisture_value) > 40 && Integer.parseInt(moisture_value) <= 70){
tv_moisture_value.setTextColor(getResources().getColor(R.color.secondary_green));
tv_moisture_stats.setText("Normal");
tv_moisture_stats.setTextColor(getResources().getColor(R.color.secondary_green));
}
else if(Integer.parseInt(moisture_value) > 70){
tv_moisture_value.setTextColor(getResources().getColor(R.color.teal_200));
tv_moisture_stats.setText("Lembab");
tv_moisture_stats.setTextColor(getResources().getColor(R.color.teal_200));
}
if(Integer.parseInt(light_value) < 100){
ic_weather_stats.setImageResource(R.drawable.ic_cuaca_cerah_berawan);
tv_weather_stats.setText("Cerah Berawan");
tv_weather_stats.setTextColor(getResources().getColor(R.color.yellow_warning));
}
else if(Integer.parseInt(light_value) >= 100){
ic_weather_stats.setImageResource(R.drawable.ic_cuaca_cerah);
tv_weather_stats.setText("Cerah");
tv_weather_stats.setTextColor(getResources().getColor(R.color.yellow_warning));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
tv_btn_show_detail_water_level = view.findViewById(R.id.tv_btn_show_detail_water_level);
tv_btn_show_detail_water_level.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getActivity().getApplicationContext(), LevelKetinggianAirAnalisisActivity.class);
startActivity(i);
}
});
tv_btn_show_detail_soil_moisture = view.findViewById(R.id.tv_btn_show_detail_soil_moisture);
tv_btn_show_detail_soil_moisture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent k = new Intent(getActivity().getApplicationContext(), KelembabanTanahAnalisisActivity.class);
startActivity(k);
}
});
tv_btn_show_detail_humidity = view.findViewById(R.id.tv_btn_show_detail_humidity);
tv_btn_show_detail_humidity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent h = new Intent(getActivity().getApplicationContext(), KelembabanUdaraAnalisisActivity.class);
startActivity(h);
}
});
tv_btn_show_detail_temperature = view.findViewById(R.id.tv_btn_show_detail_temperature);
tv_btn_show_detail_temperature.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent_data = new Intent(getActivity().getApplicationContext(), SuhuAnalisisActivity.class);
startActivity(intent_data);
}
});
// Inflate the layout for this fragment
return view;
}
#Override
public void onResume() {
super.onResume();
TextView txt_adds1 = getActivity().findViewById(R.id.txt_adds1);
TextView txt_adds2 = getActivity().findViewById(R.id.txt_adds2);
ImageView imgview_bg_appbar = getActivity().findViewById(R.id.imgview_bg_appbar);
imgview_bg_appbar.setImageResource(R.drawable.bg_appbar_dashboard);
txt_adds1.setText("Berkebun kini lebih mudah dengan");
txt_adds2.setText("digiFarm");
txt_adds2.setTextSize(TypedValue.COMPLEX_UNIT_PT, 12);
}
}
I have an error like this
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.packages.digifarm, PID: 22408
java.lang.IllegalStateException: Fragment DashboardFragment{3b25dc9} (18f94298-cd27-4447-9c7e-59cb2f952f50) not attached to a context.
at androidx.fragment.app.Fragment.requireContext(Fragment.java:900)
at androidx.fragment.app.Fragment.getResources(Fragment.java:964)
at com.packages.digifarm.ui.dashboard.DashboardFragment$1.onDataChange(DashboardFragment.java:82)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:7948)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1075)

Android about unable to start activity componentinfo

I'm a new programmer,recently i have a bug but can't solve
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.Bl
uetoothChat/com.example.android.BluetoothFileTran.FileTranActivity}:
java.lang.NullPointerException
logcat stack trace
04-26 10:19:43.613: E/BluetoothChat(21754): +++ ON CREATE +++
04-26 10:19:44.213: E/CheckPermission(21754): _bluetooth code = 1
04-26 10:19:44.213: E/BluetoothChat(21754): ++ ON START ++
04-26 10:19:44.233: E/BluetoothChat(21754): + ON RESUME +
04-26 10:19:44.233: E/CheckPermission(21754): _bluetooth code = 13
04-26 10:19:45.643: E/BluetoothChat(21754): - ON PAUSE -
04-26 10:19:47.223: E/BluetoothChat(21754): + ON RESUME +
04-26 10:19:55.093: E/BluetoothChat(21754): - ON PAUSE -
04-26 10:20:21.363: E/AndroidRuntime(21754): FATAL EXCEPTION: main
04-26 10:20:21.363: E/AndroidRuntime(21754): Process: com.example.android.BluetoothChat, PID: 21754
04-26 10:20:21.363: E/AndroidRuntime(21754): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.BluetoothChat/com.example.android.BluetoothFileTran.FileTranActivity}: java.lang.NullPointerException
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2190)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread.access$800(ActivityThread.java:139)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1200)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.os.Handler.dispatchMessage(Handler.java:102)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.os.Looper.loop(Looper.java:136)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread.main(ActivityThread.java:5049)
04-26 10:20:21.363: E/AndroidRuntime(21754): at java.lang.reflect.Method.invokeNative(Native Method)
04-26 10:20:21.363: E/AndroidRuntime(21754): at java.lang.reflect.Method.invoke(Method.java:515)
04-26 10:20:21.363: E/AndroidRuntime(21754): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:818)
04-26 10:20:21.363: E/AndroidRuntime(21754): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:634)
04-26 10:20:21.363: E/AndroidRuntime(21754): at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)
04-26 10:20:21.363: E/AndroidRuntime(21754): at dalvik.system.NativeStart.main(Native Method)
04-26 10:20:21.363: E/AndroidRuntime(21754): Caused by: java.lang.NullPointerException
04-26 10:20:21.363: E/AndroidRuntime(21754): at com.example.android.BluetoothFileTran.FileTranActivity.onCreate(FileTranActivity.java:66)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.Activity.performCreate(Activity.java:5293)
04-26 10:20:21.363: E/AndroidRuntime(21754): at de.robv.android.xposed.XposedBridge.invokeOriginalMethodNative(Native Method)
04-26 10:20:21.363: E/AndroidRuntime(21754): at de.robv.android.xposed.XposedBridge.handleHookedMethod(XposedBridge.java:631)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.Activity.performCreate(Native Method)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-26 10:20:21.363: E/AndroidRuntime(21754): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2154)
04-26 10:20:21.363: E/AndroidRuntime(21754): ... 12 more
here is Bluetoooth.java
package com.example.android.BluetoothChat;
import com.example.android.BluetoothChat.R;
import com.example.android.BluetoothChat.service.BluetoothChatService;
import com.example.android.BluetoothFileTran.FileTranActivity;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class BluetoothChat extends Activity {
public static final String SEND_FILE_NAME = "sendFileName";
public static final int REQUEST_FILE = 1000;
private static String mSendFileName ;
private Handler mOthHandler;
private static String mAddress ;
private static final String TAG = "BluetoothChat";
private static final boolean D = true;
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;
private String mConnectedDeviceName = null;
private ArrayAdapter<String> mConversationArrayAdapter;
private StringBuffer mOutStringBuffer;
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothChatService mChatService = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "+++ ON CREATE +++");
setContentView(R.layout.main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
}
#Override
public void onStart() {
super.onStart();
if(D) Log.e(TAG, "++ ON START ++");
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
} else {
if (mChatService == null) setupChat();
}
}
private void setupChat() {
Log.d(TAG, "setupChat()");
mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
mConversationView = (ListView) findViewById(R.id.in);
mConversationView.setAdapter(mConversationArrayAdapter);
mOutEditText = (EditText) findViewById(R.id.edit_text_out);
mOutEditText.setOnEditorActionListener(mWriteListener);
mSendButton = (Button) findViewById(R.id.button_send);
mSendButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TextView view = (TextView) findViewById(R.id.edit_text_out);
String message = view.getText().toString();
sendMessage(message);
}
});
mChatService = new BluetoothChatService(this, mHandler);
mOutStringBuffer = new StringBuffer("");
}
#Override
public synchronized void onResume() {
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");
if (mChatService != null) {
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
mChatService.start();
}
}
}
private TextView.OnEditorActionListener mWriteListener =
new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
//EditorInfo.IME_NULL KeyEvent.ACTION_UP
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
sendMessage(message);
}
if(D) Log.i(TAG, "END onEditorAction");
return true;
}
};
#Override
public synchronized void onPause() {
super.onPause();
if(D) Log.e(TAG, "- ON PAUSE -");
}
#Override
public void onStop() {
super.onStop();
if(D) Log.e(TAG, "-- ON STOP --");
}
#Override
public void onDestroy() {
super.onDestroy();
if (mChatService != null) mChatService.stop();
if(D) Log.e(TAG, "--- ON DESTROY ---");
}
private void sendMessage(String message) {
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
if (message.length() > 0) {
byte[] send = message.getBytes();
mChatService.write(send);
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
mConversationArrayAdapter.clear();
break;
case BluetoothChatService.STATE_CONNECTING:
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
String writeMessage = new String(writeBuf);
mConversationArrayAdapter.add("Me: " + writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
String readMessage = new String(readBuf, 0, msg.arg1);
mConversationArrayAdapter.add(mConnectedDeviceName+": " + readMessage);
break;
case MESSAGE_DEVICE_NAME:
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
// mAddress = msg.getData().getString(DEVICE_ADDRESS);
Toast.makeText(getApplicationContext(), "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(D) Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
if (resultCode == Activity.RESULT_OK) {
mAddress = data.getExtras()
.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(mAddress);
mChatService.connect(device);
}
break;
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_OK) {
setupChat();
} else {
Log.d(TAG, "BT not enabled");
Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
finish();
}
break;
case REQUEST_FILE:
if (resultCode == Activity.RESULT_OK) {
mSendFileName = data.getExtras().getString(SEND_FILE_NAME);
doSendFileByBluetooth();
}
break;
}
}
private void doSendFileByBluetooth() {
String filePath = mSendFileName.trim();
if(!filePath.equals("null")){
if(null == mOthHandler){
HandlerThread handlerThread = new HandlerThread("other_thread");
handlerThread.start();
mOthHandler = new Handler(handlerThread.getLooper());
}
mOthHandler.post(new Runnable() {
#Override
public void run() {
ContentValues cv = new ContentValues();
String uri = "file://" + mSendFileName.trim();
cv.put("uri", uri);
cv.put("destination", mAddress.trim());
cv.put("direction", 0);
Long ts = System.currentTimeMillis();
cv.put("timestamp", ts);
getContentResolver().insert(Uri.parse("content://com.android.bluetooth.opp/btopp"), cv);
}
});
}else {
Toast.makeText(BluetoothChat.this, "请选择要发送的文件!", Toast.LENGTH_LONG).show();
}
}
private void ensureDiscoverable() {
if(D) Log.d(TAG, "ensure discoverable");
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.option_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.scan:
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
return true;
case R.id.discoverable:
ensureDiscoverable();
return true;
case R.id.file_transport:
Intent fileIntent = new Intent(this, FileTranActivity.class);
startActivityForResult(fileIntent, REQUEST_FILE);
return true;
}
return false;
}
}
here is FileTranActivity.java
package com.example.android.BluetoothFileTran;
import java.io.File;
import com.example.android.BluetoothChat.BluetoothChat;
import com.example.android.BluetoothChat.R;
import com.example.android.BluetoothFileTran.adapter.AdapterManager;
import com.example.android.BluetoothFileTran.adapter.FileListAdapter;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class FileTranActivity extends Activity {
ListView mFileListView;
FileListAdapter mFileListAdapter;
AdapterManager mAdapterManager;
private Handler mOtherHandler;
private Runnable updateFileListRunnable;
private File file;
private String sdcardPath;
private String path;
Button mBackBtn;
Button mEnsureBtn;
Button mCancelBtn;
TextView mLastClickView;
TextView mNowClickView;
private boolean isSelected = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.file_list);
setResult(Activity.RESULT_CANCELED);
mFileListView = (ListView) findViewById(R.id.fileListView);
mBackBtn = (Button) findViewById(R.id.selectFileBackBtn);
mEnsureBtn = (Button) findViewById(R.id.selectFileEnsureBtn);
mCancelBtn = (Button) findViewById(R.id.selectFileCancelBtn);
sdcardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
path = sdcardPath;
mAdapterManager = BluetoothApplication.getInstance().getAdapterManager();
mFileListView.setAdapter(mAdapterManager.getFileListAdapter());
mAdapterManager.updateFileListAdapter(path);
mFileListView.setOnItemClickListener(mFileListOnItemClickListener);
mBackBtn.setOnClickListener(mBackBtnClickListener);
mEnsureBtn.setOnClickListener(mEnsureBtnClickListener);
mCancelBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FileTranActivity.this.finish();
}
});
}
private OnItemClickListener mFileListOnItemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
file = (File) mFileListView.getAdapter().getItem(position);
if(file.isFile()){
if(null != mLastClickView){
mLastClickView.setTextColor(Color.WHITE);
}
mNowClickView = (TextView) view.findViewById(R.id.fileNameTV);
mNowClickView.setTextColor(Color.BLUE);
isSelected = true;
mLastClickView = mNowClickView;
}else {
path = file.getAbsolutePath();
updateFileList();
}
}
};
private OnClickListener mBackBtnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(path.equals(sdcardPath)){
return ;
}
path = path.substring(0, path.lastIndexOf("/"));
updateFileList();
}
};
private OnClickListener mEnsureBtnClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(!isSelected){
Toast.makeText(FileTranActivity.this, "请选择文件!", Toast.LENGTH_LONG).show();
return ;
}
Intent intent = new Intent();
intent.putExtra(BluetoothChat.SEND_FILE_NAME, file.getAbsolutePath());
setResult(Activity.RESULT_OK, intent);
FileTranActivity.this.finish();
}
};
private void updateFileList() {
if(null != mLastClickView){
mLastClickView.setTextColor(Color.WHITE);
mLastClickView = null;
isSelected = false;
}
if(null == updateFileListRunnable){
updateFileListRunnable = new Runnable() {
#Override
public void run() {
mAdapterManager.updateFileListAdapter(path);
}
};
}
if(null == mOtherHandler){
HandlerThread handlerThread = new HandlerThread("other_thread");
handlerThread.start();
mOtherHandler = new Handler(handlerThread.getLooper());
}
mOtherHandler.post(updateFileListRunnable);
}
}
then ,I find it point out the error in the FileTranActivity.java
mAdapterManager = BluetoothApplication.getInstance().getAdapterManager();
so ,here is BluetoothApplication.java
package com.example.android.BluetoothFileTran;
import com.example.android.BluetoothFileTran.adapter.AdapterManager;
import com.example.android.BluetoothFileTran.adapter.util.TouchObject;
import android.app.Application;
public class BluetoothApplication extends Application {
private static BluetoothApplication application;
private AdapterManager mAdapterManager;
private TouchObject mTouchObject;
#Override
public void onCreate() {
super.onCreate();
if(null == application){
application = this;
}
mTouchObject = new TouchObject();
}
public static BluetoothApplication getInstance(){
return application;
}
public AdapterManager getAdapterManager() {
return mAdapterManager;
}
public void setAdapterManager(AdapterManager adapterManager) {
this.mAdapterManager = adapterManager;
}
public TouchObject getTouchObject() {
return mTouchObject;
}
public void setTouchObject(TouchObject touchObject) {
this.mTouchObject = touchObject;
}
}
and AdapterManager.java
package com.example.android.BluetoothFileTran.adapter;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.os.Handler;
import com.example.android.BluetoothChat.R;
import com.example.android.BluetoothFileTran.adapter.FileListAdapter;
public class AdapterManager {
private Context mContext;
private FileListAdapter mFileListAdapter;
private List<BluetoothDevice> mDeviceList;
private List<File> mFileList;
private Handler mainHandler;
public AdapterManager(Context context){
this.mContext = context;
}
public FileListAdapter getFileListAdapter(){
if(null == mFileListAdapter){
mFileList = new ArrayList<File>();
mFileListAdapter = new FileListAdapter(mContext, mFileList, R.layout.file_list_item);
}
return mFileListAdapter;
}
public void clearDevice(){
if(null != mDeviceList){
mDeviceList.clear();
}
}
public void addDevice(BluetoothDevice bluetoothDevice){
mDeviceList.add(bluetoothDevice);
}
public void changeDevice(int listId, BluetoothDevice bluetoothDevice){
mDeviceList.remove(listId);
mDeviceList.add(listId, bluetoothDevice);
}
public void updateFileListAdapter(String path){
mFileList.clear();
mFileList.addAll(getFileList(path));
if(null == mainHandler){
mainHandler = new Handler(mContext.getMainLooper());
}
mainHandler.post(new Runnable() {
#Override
public void run() {
mFileListAdapter.notifyDataSetChanged();
}
});
}
public List<BluetoothDevice> getDeviceList() {
return mDeviceList;
}
public static List<File> getFileList(String path){
List<File> fileList = new ArrayList<File>();
File[] files = new File(path).listFiles();
if(files.length > 0){
List<File> allFolder = new ArrayList<File>();
List<File> allFile = new ArrayList<File>();
for(File file : files){
if(file.isFile()){
allFile.add(file);
}else {
allFolder.add(file);
}
}
fileList.addAll(allFolder);
fileList.addAll(allFile);
}
return fileList;
}
}
my xml is
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.BluetoothChat"
android:versionCode="1"
android:versionName="1.0" xmlns:tools="http://schemas.android.com/tools">
<uses-sdk
android:minSdkVersion="6"
android:targetSdkVersion="18" tools:ignore="OldTargetApi"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:label="#string/app_name"
android:icon="#drawable/ic_launcher"
android:theme="#style/AppTheme" >
<activity android:name="com.example.android.BluetoothChat.BluetoothChat"
android:label="#string/app_name"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="com.example.android.BluetoothChat.DeviceListActivity"
android:label="#string/select_device"
android:theme="#android:style/Theme.Dialog"
/>
<activity android:name="com.example.android.BluetoothFileTran.FileTranActivity"
android:label="#string/select_file"
android:theme="#android:style/Theme.Dialog"
/>
</application>
</manifest>
Register in the AndroidManifest the BluetoothFileTran class as application name in application tag:
<application
android:allowBackup="true"
android:name="com.example.android.BluetoothFileTran"
...
Without this, the BluetoothFileTran will not be loaded, and onCreate will never invoked.
This will return a null reference in BluetoothApplication.getInstance(), which are causing your NullPointerException.
Reference
Notice: Your package in manifest, package="com.example.android.BluetoothChat" is different from the package that BluetoothFileTran is located (not in one of childs). I recommend you to use the package com.example.android instead of com.example.android.BluetoothChat in manifest tag.

Why aren't my buttons working?

So I recently made my first app and went out to test it. When I opened the app on my phone I got 2 problems. The menu off my app does have 3 buttons, 1 to start a "1player game" 1 to start a "2player game" and 1 to exit the app. When I press the button to play a "1player game" there happens nothing. When I press the "2player game" button, the app closes with the error "unfortunately testjk was closed". I have literally no idea what I did wrong in my code. I also have no erros in my problems tab. Some help would be appreciated.
MainMenuScreen.java:
package com.wouter.testjk;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
public class MainMenuScreen extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main_menu);
//1player
findViewById(R.id.two_player).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("DEBUG", "One Player Button Pressed!");
Intent intent = new Intent(MainMenuScreen.this, TicTacToeGame.class);
intent.putExtra("gameType", true);
startActivityForResult(intent, 0);
}
});
//2players
findViewById(R.id.two_player).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Log.d("DEBUG", "Two Player Button Pressed!");
Intent intent = new Intent(MainMenuScreen.this, TicTacToeGame.class);
intent.putExtra("gameType", false);
startActivityForResult(intent, 0);
}
});
//exit game
findViewById(R.id.exit_game).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Log.d("DEBUG", "Exit Game Button Pressed!");
MainMenuScreen.this.finish();
}
});
}
}
MainActivity.java:
package com.wouter.testjk;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import com.wouter.testjk.R;
public class MainActivity extends Activity implements OnClickListener{
private TicTacToeGame mGame;
private Button mBoardButtons[];
private TextView mInfoTextView;
private TextView mPlayeroneCount;
private TextView mTieCount;
private TextView mPlayertwoCount;
private TextView mPlayeroneText;
private TextView mPlayertwoText;
private int mPlayeroneCounter = 0;
private int mTieCounter = 0;
private int mPlayertwoCounter = 0;
private boolean mPlayeroneFirst = true;
private boolean mIsSinglePlayer = false;
private boolean mIsPlayerOneTurn = true;
private boolean mGameOver = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
boolean mGameType = getIntent().getExtras().getBoolean("gametype");
mBoardButtons = new Button[mGame.getBOARD_SIZE()];
mBoardButtons[0] = (Button) findViewById(R.id.one);
mBoardButtons[1] = (Button) findViewById(R.id.two);
mBoardButtons[2] = (Button) findViewById(R.id.three);
mBoardButtons[3] = (Button) findViewById(R.id.four);
mBoardButtons[4] = (Button) findViewById(R.id.five);
mBoardButtons[5] = (Button) findViewById(R.id.six);
mBoardButtons[6] = (Button) findViewById(R.id.seven);
mBoardButtons[7] = (Button) findViewById(R.id.eight);
mBoardButtons[8] = (Button) findViewById(R.id.nine);
Button mTen = (Button) findViewById(R.id.ten);
mTen.setOnClickListener(this);
Button mEleven = (Button) findViewById(R.id.eleven);
mEleven.setOnClickListener(this);
mInfoTextView = (TextView) findViewById(R.id.information);
mPlayeroneCount = (TextView) findViewById(R.id.humancount);
mTieCount = (TextView) findViewById(R.id.tiesCount);
mPlayertwoCount = (TextView) findViewById(R.id.androidCount);
mPlayeroneText = (TextView) findViewById(R.id.human);
mPlayertwoText = (TextView) findViewById(R.id.android);
mPlayeroneCount.setText(Integer.toString(mPlayeroneCounter));
mTieCount.setText(Integer.toString(mTieCounter));
mPlayeroneCount.setText(Integer.toString(mPlayertwoCounter));
mGame = new TicTacToeGame();
startNewGame(mGameType);
}
private void startNewGame(boolean isSingle)
{
this.mIsSinglePlayer = isSingle;
mGame.clearBoard();
for (int i = 0; i < mBoardButtons.length; i++)
{
mBoardButtons[i].setText("");
mBoardButtons[i].setEnabled(true);
mBoardButtons[i].setOnClickListener(new ButtonClickListener(i));
}
if (mIsSinglePlayer)
{
mPlayeroneText.setText("speler: ");
mPlayertwoText.setText("android: ");
if (mPlayeroneFirst)
{
mInfoTextView.setText(R.string.first_human);
mPlayeroneFirst = false;
}
else
{
mInfoTextView.setText(R.string.turn_computer);
int move = mGame.getComputerMove();
setMove(TicTacToeGame.PLAYER_TWO, move);
mPlayeroneFirst = true;
}
}
else
{
mPlayeroneText.setText("speler 1: ");
mPlayertwoText.setText("speler 2: ");
if (mPlayeroneFirst)
{
mInfoTextView.setText(R.string.turn_player_one);
mPlayeroneFirst = false;
}
else
{
mInfoTextView.setText(R.string.turn_player_two);
mPlayeroneFirst = true;
}
}
mGameOver = false;
}
private class ButtonClickListener implements View.OnClickListener
{
int location;
public ButtonClickListener(int location)
{
this.location = location;
}
#Override
public void onClick(View view) {
if (!mGameOver)
{
if(mBoardButtons[location].isEnabled())
{
if(mIsSinglePlayer)
{
setMove(TicTacToeGame.PLAYER_ONE, location);
int winner = mGame.checkForWinner();
if (winner == 0)
{
mInfoTextView.setText(R.string.turn_computer);
int move = mGame.getComputerMove();
setMove(TicTacToeGame.PLAYER_TWO, move);
winner = mGame.checkForWinner();
}
if (winner == 0)
mInfoTextView.setText(R.string.turn_human);
else if (winner == 1)
{
mInfoTextView.setText(R.string.result_tie);
mTieCounter++;
mTieCount.setText(Integer.toString(mTieCounter));
mGameOver = true;
}
else if (winner ==2)
{
mInfoTextView.setText(R.string.result_human_wins);
mPlayeroneCounter++;
mPlayeroneCount.setText(Integer.toString(mPlayeroneCounter));
mGameOver = true;
}
else if (winner ==3)
{
mInfoTextView.setText(R.string.result_android_wins);
mPlayertwoCounter++;
mPlayertwoCount.setText(Integer.toString(mPlayertwoCounter));
mGameOver = true;
}
}
else
{
if(mIsPlayerOneTurn)
{
setMove(TicTacToeGame.PLAYER_ONE, location);
}
else
{
setMove(TicTacToeGame.PLAYER_TWO, location);
}
int winner = mGame.checkForWinner();
if (winner == 0)
{
if(mIsPlayerOneTurn)
{
mInfoTextView.setText(R.string.turn_player_two);
mIsPlayerOneTurn = false;
}
else
{
mInfoTextView.setText(R.string.turn_player_one);
mIsPlayerOneTurn = true;
}
}
else if (winner == 1)
{
mInfoTextView.setText(R.string.result_tie);
mTieCounter++;
mTieCount.setText(Integer.toString(mTieCounter));
mGameOver = true;
}
else if (winner ==2)
{
mInfoTextView.setText(R.string.player_one_wins);
mPlayeroneCounter++;
mPlayeroneCount.setText(Integer.toString(mPlayeroneCounter));
mGameOver = true;
}
else if (winner ==3)
{
mInfoTextView.setText(R.string.player_two_wins);
mPlayertwoCounter++;
mPlayertwoCount.setText(Integer.toString(mPlayertwoCounter));
mGameOver = true;
}
}
}
}
}
}
private void setMove(char player, int location)
{
mGame.setMove(player,location);
mBoardButtons[location].setEnabled(false);
if (player == TicTacToeGame.PLAYER_ONE)
mBoardButtons[location].setTextColor(Color.GREEN);
else
{
mBoardButtons[location].setTextColor(Color.RED);
}
}
#Override
public void onClick(View view) {
switch (view.getId())
{
case R.id.ten:
startNewGame(mIsSinglePlayer);
return;
case R.id.eleven:
MainActivity.this.finish();
return;
}
}
}
manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.wouter.testjk"
android:versionCode="3"
android:versionName="3" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainMenuScreen"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
LogCat: http://textuploader.com/on1k --------
http://imgur.com/d8662NO -----------
I have no idea how else I should upload this
You are assigning both OnClickListeners to the same button R.id.two_player. That is, change the first one to one_player, as
// 1player
findViewById(R.id.one_player).setOnClickListener(new View.OnClickListener() {
// (...)
});
//2players
findViewById(R.id.two_player).setOnClickListener(new View.OnClickListener() {
// (...)
});
EDIT: as I see in the logcat, and also correctly pointed by Spidy in the comments, you need to declare your activity in the manifest.
11-15 23:45:28.227: E/AndroidRuntime(6056): FATAL EXCEPTION: main
11-15 23:45:28.227: E/AndroidRuntime(6056): android.content.ActivityNotFoundException: Unable to find explicit activity class {com.wouter.testjk/com.wouter.testjk.TicTacToeGame}; have you declared this activity in your AndroidManifest.xml?
EDIT2: It's pretty clear from the logs:
11-16 00:39:09.867: E/AndroidRuntime(7124): FATAL EXCEPTION: main
11-16 00:39:09.867: E/AndroidRuntime(7124): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.wouter.testjk/com.wouter.testjk.TicTacToeGame}: java.lang.ClassCastException: com.wouter.testjk.TicTacToeGame cannot be cast to android.app.Activity
You are trying to instantiate the class TicTacToeGame as an activity, but it is not. I guess you wanted to go to the MainActivity. In that case, you must change your intent to something like this
Intent intent = new Intent(MainMenuScreen.this, MainActivity.class);
Hope it helps.

Stuck, need help Program crashes whenever it tries to access the SharedPreferences

Program runs until it tries to access the SharedPreferences in my updateUserSettings() method. I have spent the last 2 hours searching the internet with no explanations. Please help!
I have the line that messes everything up Commented at the bottom of my onCreate();
Here is FuelEconomyCalculatorActivity.java
package com.example.fuelcalculator;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class FuelEconomyCalculatorActivity extends ActionBarActivity implements
OnClickListener {
private EditText fuelEditText;
private EditText distanceEditText;
private TextView mpgTextView;
private TextView litresTextView;
private Button calculateButton;
private Button clearButton;
private RadioButton gallonsRadio;
private RadioButton litresRadio;
private RadioButton milesRadio;
private RadioButton kmRadio;
private String mpg = " ";
private String kp100 = " ";
private boolean metricChecked;
private boolean imperialChecked;
private boolean usGallonChecked;
private boolean ukGallonChecked;
private static final int RESULT_SETTINGS = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fuel_economy_calculator);
fuelEditText = (EditText) findViewById(R.id.fuelEditText);
distanceEditText = (EditText) findViewById(R.id.distanceEditText);
mpgTextView = (TextView) findViewById(R.id.mpgTextView);
litresTextView = (TextView) findViewById(R.id.litresTextView);
calculateButton = (Button) findViewById(R.id.calculateButton);
clearButton = (Button) findViewById(R.id.clearButton);
gallonsRadio = (RadioButton) findViewById(R.id.gallonsRadio);
litresRadio = (RadioButton) findViewById(R.id.litresRadio);
milesRadio = (RadioButton) findViewById(R.id.milesRadio);
kmRadio = (RadioButton) findViewById(R.id.kmRadio);
calculateButton.setOnClickListener(this);
clearButton.setOnClickListener(this);
if (savedInstanceState != null) {
mpg = savedInstanceState.getString("mpg");
kp100 = savedInstanceState.getString("kp100");
initializeViews();
}
// updateUserSettings();
}
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("mpg", (String) mpgTextView.getText());
savedInstanceState.putString("kp100", (String) litresTextView.getText());
litresRadio.setChecked(true);
kmRadio.setChecked(true);
}
private void initializeViews() {
mpgTextView.setText(mpg);
litresTextView.setText(kp100);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.fuel_economy_calculator, 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.
switch (item.getItemId()) {
case R.id.action_settings: {
Intent intent = new Intent(FuelEconomyCalculatorActivity.this,
FuelEconomySettingsActivity.class);
startActivityForResult(intent, RESULT_SETTINGS);
return true;
}
case R.id.action_about: {
Intent intent = new Intent(getApplicationContext(), FuelEconomyAboutPageActivity.class);
startActivity(intent);
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_SETTINGS:
updateUserSettings();
break;
}
}
private void updateUserSettings() {
SharedPreferences sharedPrefs = PreferenceManager
.getDefaultSharedPreferences(this);
if(sharedPrefs.getString("measuringUnits", null).equalsIgnoreCase("metric"))
{
metricChecked = true;
imperialChecked = false;
}
else if(sharedPrefs.getString("measuringUnits", null).equalsIgnoreCase("imperial"))
{
imperialChecked = true;
metricChecked = false;
}
if(sharedPrefs.getString("gallons", null).equalsIgnoreCase("uk"))
{
ukGallonChecked = true;
usGallonChecked = false;
}
else if(sharedPrefs.getString("gallons", null).equalsIgnoreCase("us"))
{
usGallonChecked = true;
ukGallonChecked = false;
}
if(metricChecked)
{
litresRadio.setChecked(true);
kmRadio.setChecked(true);
}
else if(imperialChecked)
{
milesRadio.setChecked(true);
gallonsRadio.setChecked(true);
}
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.calculateButton) {
float mpg = 0;
float kmLitres = 0;
// it doesn't matter which you use here, as long
// as you use a fuel and a distance method
if (ukGallonChecked && !usGallonChecked) {
if (getKM() > 0 && getLitres() > 0) {
mpg = getMiles() / getGallons();
kmLitres = getLitres() / (getKM() / 100);
mpgTextView.setText(String.format("%.2f", mpg));
litresTextView.setText(String.format("%.2f", kmLitres));
}
} else if (usGallonChecked && !ukGallonChecked) {
if (getKM() > 0 && getLitres() > 0) {
mpg = getMiles() / getGallonsUS();
kmLitres = getLitresUS() / (getKM() / 100);
mpgTextView.setText(String.format("%.2f", mpg));
litresTextView.setText(String.format("%.2f", kmLitres));
}
}
} else if (v.getId() == R.id.clearButton) {
resetValues();
}
}
public float CheckValues(EditText input) {
float value = 0;
try {
value = Float.parseFloat(input.getText().toString());
if (value < 1) {
Toast toast = Toast.makeText(this,
"Please enter a number that is larger than 0",
Toast.LENGTH_SHORT);
toast.show();
}
} catch (Exception ex) {
Toast toast = Toast.makeText(this, "Please enter a number",
Toast.LENGTH_SHORT);
toast.show();
}
return value;
}
public void resetValues() {
mpg = " ";
kp100 = " ";
fuelEditText.setText("");
distanceEditText.setText("");
mpgTextView.setText("");
litresTextView.setText("");
}
public float getKM() {
float distance = CheckValues(distanceEditText);
if (milesRadio.isChecked()) {
distance = (float) (distance * 1.60934);
}
return distance;
}
public float getMiles() {
float distance = CheckValues(distanceEditText);
if (kmRadio.isChecked()) {
distance = (float) (distance * 0.62137);
}
return distance;
}
public float getLitres() {
float fuel = CheckValues(fuelEditText);
if (gallonsRadio.isChecked()) {
fuel = (float) (fuel * 4.54609);
}
return fuel;
}
public float getLitresUS() {
float fuel = CheckValues(fuelEditText);
if (gallonsRadio.isChecked()) {
fuel = (float) (fuel * 3.785411784);
}
return fuel;
}
public float getGallons() {
float fuel = CheckValues(fuelEditText);
if (litresRadio.isChecked()) {
fuel = (float) (fuel * 0.219969);
}
return fuel;
}
public float getGallonsUS() {
float fuel = CheckValues(fuelEditText);
if (litresRadio.isChecked()) {
fuel = (float) (fuel * 0.264172);
}
return fuel;
}
}
And here is my FuelEconomySettingsActivity.java
package com.example.fuelcalculator;
import android.app.Activity;
import android.os.Bundle;
public class FuelEconomySettingsActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction().replace(android.R.id.content,
new FuelEconomySettingsFragment()).commit();
}
}
Here is my LogCat
07-18 14:35:37.014: E/AndroidRuntime(3084): FATAL EXCEPTION: main
07-18 14:35:37.014: E/AndroidRuntime(3084): Process: com.example.fuelcalculator, PID: 3084
07-18 14:35:37.014: E/AndroidRuntime(3084): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fuelcalculator/com.example.fuelcalculator.FuelEconomyCalculatorActivity}: java.lang.NullPointerException
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread.access$900(ActivityThread.java:161)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.os.Handler.dispatchMessage(Handler.java:102)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.os.Looper.loop(Looper.java:157)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread.main(ActivityThread.java:5356)
07-18 14:35:37.014: E/AndroidRuntime(3084): at java.lang.reflect.Method.invokeNative(Native Method)
07-18 14:35:37.014: E/AndroidRuntime(3084): at java.lang.reflect.Method.invoke(Method.java:515)
07-18 14:35:37.014: E/AndroidRuntime(3084): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
07-18 14:35:37.014: E/AndroidRuntime(3084): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
07-18 14:35:37.014: E/AndroidRuntime(3084): at dalvik.system.NativeStart.main(Native Method)
07-18 14:35:37.014: E/AndroidRuntime(3084): Caused by: java.lang.NullPointerException
07-18 14:35:37.014: E/AndroidRuntime(3084): at com.example.fuelcalculator.FuelEconomyCalculatorActivity.updateUserSettings(FuelEconomyCalculatorActivity.java:128)
07-18 14:35:37.014: E/AndroidRuntime(3084): at com.example.fuelcalculator.FuelEconomyCalculatorActivity.onCreate(FuelEconomyCalculatorActivity.java:63)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.Activity.performCreate(Activity.java:5426)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
07-18 14:35:37.014: E/AndroidRuntime(3084): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
07-18 14:35:37.014: E/AndroidRuntime(3084): ... 11 more
I am new to Android so I am not very good at debugging so could someone please assist me with my predicament?
The activity is already included in my Manifest so I know that is not the issue.
Any help is much obliged.
You are getting a NullPointerException because you are getting null as the default value for SharedPreference.getString()
Since it is getString() get an empty string as the default value...
So try this..
if(sharedPrefs.getString("measuringUnits", "").equalsIgnoreCase("metric"))
instead of
if(sharedPrefs.getString("measuringUnits", null).equalsIgnoreCase("metric"))

Google places tutorial NPE android

I am trying to do a google places tutorial i found on the net.But i am getting NPE in a certain class:
ShowGoogleMap.java
package com.gmap;
import java.util.List;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
public class ShowGoogleMap extends MapActivity {
protected static int updated_lat;
protected static int updated_lng;
// Used to add overlay markers of both type
List<Overlay> listOfOverlays;
private boolean isPotentialLongPress;
ProgressDialog progressDialog;
// adding your own place info
static double addLat = 0;
static double addLng = 0;
static String locType = "cafe";
static String LocName = "OffCourse Golf Hole";
static String detailText;
Button reloadButton;
Button placeDetailsButton;
Button addPlaceButton;
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.showmap);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setStreetView(true);
//mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(14); // Zoom 1 is world view
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new GeoUpdateHandler());
reloadButton = (Button)findViewById(R.id.relaod);
placeDetailsButton = (Button)findViewById(R.id.place_details);
addPlaceButton = (Button)findViewById(R.id.add_place);
// set place Button listener here
reloadButton.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
SearchSrv srv = new SearchSrv();
setProgressBarIndeterminateVisibility(true);
srv.execute();
}
});
// set Detail Button listener here
placeDetailsButton.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
if (MyItemizedOverlay.reference == null) {
Toast.makeText(getBaseContext(), "Please select your place marker first!", Toast.LENGTH_SHORT).show();
}else{
DetailSrv srv = new DetailSrv();
setProgressBarIndeterminateVisibility(true);
srv.execute();
}
}
});
// To show an AlertDialog Box
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Please select your location by long pressing")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// set add place Button listener here
addPlaceButton.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
if (addLat == 0 && addLng == 0){
AlertDialog alert = builder.create();
alert.show();
}
else{
Intent myIntent = new Intent(getBaseContext(), PlaceAdd.class);
startActivityForResult(myIntent, 0);
setProgressBarIndeterminateVisibility(false);
}
}
});
} // end onCreate() method here
private class SearchSrv extends AsyncTask<Void, Void, PlacesList>{
#Override
protected PlacesList doInBackground(Void... params) {
PlacesList pl = null;
try {
// send place search request from here
pl = new PlaceRequest().performSearch();
} catch (Exception e) {
e.printStackTrace();
}
return pl;
}
#Override
protected void onPostExecute(PlacesList result) {
Drawable marker=getResources().getDrawable(R.drawable.places_marker);
int markerWidth = marker.getIntrinsicWidth();
int markerHeight = marker.getIntrinsicHeight();
marker.setBounds(0, markerHeight, markerWidth, 0);
for(int i = 0; i < listOfOverlays.size(); i++){
if (i != 0){
listOfOverlays.remove(i);
}
}
// Here place searched are displayed on google map as Red markers
if (result != null) {
int []lat = new int[PlaceRequest.latList.size()];
int []lng = new int[PlaceRequest.lngList.size()];
MyItemizedOverlay myItemizedOverlay = new MyItemizedOverlay(marker, ShowGoogleMap.this);
listOfOverlays = mapView.getOverlays();
listOfOverlays.add(myItemizedOverlay);
for(int i = 0; i< PlaceRequest.latList.size(); i++) {
lat[i] = (int)(PlaceRequest.latList.get(i) * 1E6);
lng[i] = (int)(PlaceRequest.lngList.get(i) * 1E6);
Log.v("GPS", "My Place Location is: "+ lat[i] + "," + lng[i]);
GeoPoint point = new GeoPoint(lat[i], lng[i]);
myItemizedOverlay.addItem(point, "OffCourse Golf Hole "+i, PlaceRequest.placeReference.get(i).toString());
}
} else{
Toast.makeText(getBaseContext(), "Please Try Again", Toast.LENGTH_SHORT).show();
}
setProgressBarIndeterminateVisibility(false);
}
} // End of class SearchSrv here
private class DetailSrv extends AsyncTask<Void, Void, PlaceDetail>{
#Override
protected PlaceDetail doInBackground(Void... params) {
PlaceDetail pl = null;
try {
// send place search request from here
pl = new PlaceRequest().performDetails(MyItemizedOverlay.reference);
} catch (Exception e) {
e.printStackTrace();
}
return pl;
}
#Override
protected void onPostExecute(PlaceDetail details) {
Log.v(PlaceRequest.LOG_KEY, "Place details JSON format: " + details);
//to display place Details
detailText = "Place Details\n\n";
if (details != null) {
Place place = details.result;
detailText = detailText + "id = " + place.id +"\n";
detailText = detailText + "name = " + place.name +"\n";
detailText = detailText + "reference = " + place.reference +"\n";
detailText = detailText + "types = " + place.types[0]+"\n";
detailText = detailText + "phone_number = " + place.international_phone_number+"\n";
detailText = detailText + "url = " + place.url +"\n";
detailText = detailText + "vicinity = " + place.vicinity +"\n";
detailText = detailText + "website = " + place.website +"\n";
detailText = detailText + "rating = " + place.rating +"\n";
detailText = detailText + "formatted_address = " + place.formatted_address +"\n";
detailText = detailText + "lat = " + place.geometry.location.lat +"\n";
detailText = detailText + "lng = " + place.geometry.location.lng +"\n";
Log.v(PlaceRequest.LOG_KEY, "Details = " + detailText );
}
// To show my My Custom Dialog box: DetailDialog
Intent myIntent = new Intent(getBaseContext(), ShowPlaceDetail.class);
startActivityForResult(myIntent, 0);
setProgressBarIndeterminateVisibility(false);
}
} // End of class SearchSrv here
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
handleLongPress(event);
return super.dispatchTouchEvent(event);
}
// Here detecting user long press to add my own place
private void handleLongPress( final MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// A new touch has been detected
new Thread(new Runnable() {
public void run() {
Looper.prepare();
if (isLongPressDetected()) {
// We have a long press! Perform your action here
GeoPoint p = mapView.getProjection().fromPixels((int) event.getX(), (int) event.getY());
addLat = p.getLatitudeE6() / 1E6;
addLng = p.getLongitudeE6() / 1E6;
Log.v("Long Press", "Location on Touch: " + p.getLatitudeE6() / 1E6+ "," +p.getLongitudeE6() / 1E6);
}
}
}).start();
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
if (event.getHistorySize() < 1)
return; // First call, no history
// Get difference in position since previous move event
float diffX = event.getX() - event.getHistoricalX(event.getHistorySize() - 1);
float diffY = event.getY() - event.getHistoricalY(event.getHistorySize() - 1);
/* If position has moved substatially, this is not a long press but probably a drag action */
if (Math.abs(diffX) > 0.5f || Math.abs(diffY) > 0.5f) {
isPotentialLongPress = false;
}
} else {
// This motion is something else, and thus not part of a longpress
isPotentialLongPress = false;
}
}
public boolean isLongPressDetected() {
isPotentialLongPress = true;
try {
for (int i = 0; i < 50; i++) {
Thread.sleep(10);
if (!isPotentialLongPress) {
return false;
}
}
return true;
} catch (InterruptedException e) {
return false;
} finally {
isPotentialLongPress = false;
}
}
public class GeoUpdateHandler implements LocationListener {
// To get user current location (latitude, longitude)
public void onLocationChanged(Location location) {
updated_lat = (int) (location.getLatitude() * 1E6);
updated_lng = (int) (location.getLongitude() * 1E6);
Log.v("GPS", "Updated Lat , Updated Lng: "+ updated_lat + "," + updated_lng);
GeoPoint point = new GeoPoint(updated_lat, updated_lng);
mapController.animateTo(point); // mapController.setCenter(point);
listOfOverlays = mapView.getOverlays();
if (listOfOverlays.isEmpty()){
listOfOverlays.add(new MapOverlay(point));
}
else{
// replace it
listOfOverlays.set(0, new MapOverlay(point));
}
mapView.invalidate();
}
// Overlay for for user current location
class MapOverlay extends Overlay {
GeoPoint point = null;
MapOverlay (GeoPoint point){
this.point = point;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
super.draw(canvas, mapView, shadow);
//---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
mapView.getProjection().toPixels(point, screenPts);
//---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.user_marker);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-33, null); // 33 is height of marker
return true;
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
LOGCAT:
07-01 14:06:38.187: E/AndroidRuntime(14123): FATAL EXCEPTION: main
07-01 14:06:38.187: E/AndroidRuntime(14123): java.lang.NullPointerException
07-01 14:06:38.187: E/AndroidRuntime(14123): at com.gmap.ShowGoogleMap$SearchSrv.onPostExecute(ShowGoogleMap.java:159)
07-01 14:06:38.187: E/AndroidRuntime(14123): at com.gmap.ShowGoogleMap$SearchSrv.onPostExecute(ShowGoogleMap.java:1)
07-01 14:06:38.187: E/AndroidRuntime(14123): at android.os.AsyncTask.finish(AsyncTask.java:417)
07-01 14:06:38.187: E/AndroidRuntime(14123): at android.os.AsyncTask.access$300(AsyncTask.java:127)
07-01 14:06:38.187: E/AndroidRuntime(14123): at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
07-01 14:06:38.187: E/AndroidRuntime(14123): at android.os.Handler.dispatchMessage(Handler.java:99)
07-01 14:06:38.187: E/AndroidRuntime(14123): at android.os.Looper.loop(Looper.java:130)
07-01 14:06:38.187: E/AndroidRuntime(14123): at android.app.ActivityThread.main(ActivityThread.java:3689)
07-01 14:06:38.187: E/AndroidRuntime(14123): at java.lang.reflect.Method.invokeNative(Native Method)
07-01 14:06:38.187: E/AndroidRuntime(14123): at java.lang.reflect.Method.invoke(Method.java:507)
07-01 14:06:38.187: E/AndroidRuntime(14123): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
07-01 14:06:38.187: E/AndroidRuntime(14123): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
07-01 14:06:38.187: E/AndroidRuntime(14123): at dalvik.system.NativeStart.main(Native Method)
Please help..I am new to the google maps and places api.So i dont fully understand the code from the tutorial.
Yo have to initialise your arraylist oh listOfOverlays before you are using it.
Initialize listOfOverlays like this:
List<Overlay> listOfOverlays = new ArrayList<Overlay>();
That will remove NPE.

Categories