Open second activity after clicking a specific radio button, otherwise, show message - java

I am rather new to Android/Java programming and looking for some help with a very, very basic app that I am working with. I am purely building this just to get used to Java coding and building applications for Droids, so bear with me.
I have 10 radio buttons grouped together and only one of them is the right answer (button #10). If the user clicks on any of them 1-9 I have it displaying a message that says "sorry try again", but if they click on #10, I want it to take them to a new activity, namely a page where I will put up some graphics and text that says congraulations and things of that nature. The buttons work fine for 1-9, but when I click on #10 I am gettinga force close error.
Here's what I have so far:
public class MainQuiz extends Activity implements OnCheckedChangeListener, android.widget.RadioGroup.OnCheckedChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_quiz);
((RadioGroup)findViewById(R.id.radio_group)).setOnCheckedChangeListener(this);}
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
String numeral = null;
if (checkedId == R.id.button1) {
numeral = "Nope, try again!";
} else if (checkedId == R.id.button2) {
numeral = "Nope, try again!";
} else if (checkedId == R.id.button3) {
numeral = "Nope, try again!";
}
else if (checkedId == R.id.button4) {
numeral = "Nope, try again!";
}
else if (checkedId == R.id.button5) {
numeral = "Nope, try again!";
}
else if (checkedId == R.id.button6) {
numeral = "Nope, try again!";
}
else if (checkedId == R.id.button7) {
numeral = "Nope, try again!";
}
else if (checkedId == R.id.button8) {
numeral = "Nope, try again!";
}
else if (checkedId == R.id.button9) {
numeral = "Nope, try again!";
}
else if (checkedId == R.id.button10) {
Intent myIntent = new Intent(MainQuiz.this, CorrectAnswer.class);
MainQuiz.this.startActivity(myIntent);
}
Toast.makeText(getApplicationContext(), ""+numeral+"",
Toast.LENGTH_SHORT).show(); }
Any help would be apprecitaed, I am sure this is a simple fix and I am sure it is something glaring in the syntax and code that I have messed up, but again, I am new :)
Thanks!
Here is the log after the Force Close:
11-14 13:56:48.982: D/AndroidRuntime(862): Shutting down VM
11-14 13:56:48.982: W/dalvikvm(862): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
11-14 13:56:48.992: E/AndroidRuntime(862): FATAL EXCEPTION: main
11-14 13:56:48.992: E/AndroidRuntime(862): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.test.quiz/com.test.quiz.CorrectAnswer}: java.lang.ClassCastException: com.test.quiz.CorrectAnswer
11-14 13:56:48.992: E/AndroidRuntime(862): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
11-14 13:56:48.992: E/AndroidRuntime(862): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
11-14 13:56:48.992: E/AndroidRuntime(862): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
11-14 13:56:48.992: E/AndroidRuntime(862): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
11-14 13:56:48.992: E/AndroidRuntime(862): at android.os.Handler.dispatchMessage(Handler.java:99)
11-14 13:56:48.992: E/AndroidRuntime(862): at android.os.Looper.loop(Looper.java:123)
11-14 13:56:48.992: E/AndroidRuntime(862): at android.app.ActivityThread.main(ActivityThread.java:4627)
11-14 13:56:48.992: E/AndroidRuntime(862): at java.lang.reflect.Method.invokeNative(Native Method)
11-14 13:56:48.992: E/AndroidRuntime(862): at java.lang.reflect.Method.invoke(Method.java:521)
11-14 13:56:48.992: E/AndroidRuntime(862): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-14 13:56:48.992: E/AndroidRuntime(862): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-14 13:56:48.992: E/AndroidRuntime(862): at dalvik.system.NativeStart.main(Native Method)
11-14 13:56:48.992: E/AndroidRuntime(862): Caused by: java.lang.ClassCastException: com.test.quiz.CorrectAnswer
11-14 13:56:48.992: E/AndroidRuntime(862): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
11-14 13:56:48.992: E/AndroidRuntime(862): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
11-14 13:56:48.992: E/AndroidRuntime(862): ... 11 more

The force close will always put an exception stack trace in your logcat file. Please put this in future posts, it tells us what line crashed and why.
My guess from your code and newness to Android- you probably didn't add the CorrectAnswer activity to your manifest.

I don't know what is your problem, but you can improve your code:
use "switch - case" construction.
switch (chekedId) {
case R.id.button10:
Intent myIntent = new Intent(MainQuiz.this, CorrectAnswer.class);
startActivity(myIntent);
break;
default:
Toast.makeText(getApplicationContext(), "Nope, try again!",
Toast.LENGTH_SHORT).show();
}

It seems like this line is probably what is causing your problems.
MainQuiz.this.startActivity(myIntent);
Remove the MainQuiz, and it should work
this.startActivity(myIntent);

MainQuiz.this.startActivity(myIntent);
replace by
startActivity(myIntent);

Related

Cannot update text in EditText inside onActivityResult

I am trying to use Voice Recognition on Android. Following is my code.
This is the code of the Button that is responsible to start speech recognition.
speak.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "City Name Please?");
startActivityForResult(intent, REQUEST_CODE);
}});
Here is a onActivityResult method.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<String> matches_Text = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Log.v("Results", matches_Text.get(0).toString());
//Update EditText cityname here
String normalized_cityname = matches_Text.get(0).toString().trim();
normalized_cityname = normalized_cityname.replace(" ","%20");
try {
getResponseString("http://api.openweathermap.org/data/2.5/weather?q="+normalized_cityname+"&units=metric", true);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
The code worked ok but there are two problems I am encountering now and I am afraid that they may be related.
If I try to update text in an EditText instance cityname using cityname.setText(matches_Text.get(0).toString()), it crashes the app.
If I hit the speak button now, the google voice dialog comes up but shows can't reacg google at the moment.
Please suggest what can I do?
Adding the getResponseString method also.
public void getResponseString(String Url, boolean IsCalledOnVoiceInput) throws IOException, JSONException {
String temperature="";
String city;
String country;
String weather_main, weather_description;
MyAsyncTask xxx = new MyAsyncTask();
try {
String responseString = xxx.execute(Url).get();
TextView txtTemp = (TextView)findViewById(R.id.txt_temp);
TextView txtCity = (TextView)findViewById(R.id.txt_CityName);
TextView txtWeatherMain = (TextView)findViewById(R.id.textView2);
TextView txtWeatherDescription = (TextView)findViewById(R.id.textView3);
JSONObject reader = new JSONObject(responseString);
JSONObject main = reader.getJSONObject("main");
temperature = main.getString("temp");
Log.v("temperarure",temperature);
city = reader.getString("name");
Log.v("city",city);
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
Log.v("country",country);
JSONArray weather = reader.getJSONArray("weather");
JSONObject weather_obj = weather.getJSONObject(0);
weather_main = weather_obj.getString("main");
weather_description = weather_obj.getString("description");
txtTemp.setText(temperature+" °C");
txtCity.setText(city+" ("+country+")");
txtWeatherMain.setText(weather_main);
txtWeatherDescription.setText(weather_description);
if(IsCalledOnVoiceInput)
Speak_Weather_Data(city,temperature,weather_main,weather_description);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e){
e.printStackTrace();
}
}
Here is the log output
12-24 13:36:06.050 12164-12164/samarth.learning.http D/dalvikvm﹕ Late-enabling CheckJNI
12-24 13:36:06.300 12164-12164/samarth.learning.http D/Network﹕ Network
12-24 13:36:06.300 12164-12164/samarth.learning.http V/Lat﹕ 28.8331443
12-24 13:36:06.300 12164-12164/samarth.learning.http V/Long﹕ 78.7717138
12-24 13:36:06.360 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libEGL_adreno.so
12-24 13:36:06.370 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libGLESv1_CM_adreno.so
12-24 13:36:06.380 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libGLESv2_adreno.so
12-24 13:36:06.380 12164-12164/samarth.learning.http I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build: (CL4169980)
OpenGL ES Shader Compiler Version: 17.01.10.SPL
Build Date: 11/04/13 Mon
Local Branch:
Remote Branch:
Local Patches:
Reconstruct Branch:
12-24 13:36:06.430 12164-12164/samarth.learning.http D/OpenGLRenderer﹕ Enabling debug mode 0
12-24 13:36:06.531 12164-12164/samarth.learning.http E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
12-24 13:36:06.531 12164-12164/samarth.learning.http E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
12-24 13:36:08.232 12164-12164/samarth.learning.http W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection
12-24 13:36:18.844 12164-12164/samarth.learning.http V/Results﹕ new delhi
12-24 13:36:18.844 12164-12164/samarth.learning.http D/AndroidRuntime﹕ Shutting down VM
12-24 13:36:18.844 12164-12164/samarth.learning.http W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4157c8b0)
12-24 13:36:18.854 12164-12164/samarth.learning.http E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1234, result=-1, data=Intent { (has extras) }} to activity {samarth.learning.http/samarth.learning.http.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3462)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3505)
at android.app.ActivityThread.access$1100(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1346)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at samarth.learning.http.MainActivity.onActivityResult(MainActivity.java:160)
at android.app.Activity.dispatchActivityResult(Activity.java:5322)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3458)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3505)
            at android.app.ActivityThread.access$1100(ActivityThread.java:150)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1346)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:213)
            at android.app.ActivityThread.main(ActivityThread.java:5225)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
            at dalvik.system.NativeStart.main(Native Method)
12-24 13:36:22.558 12164-12164/samarth.learning.http I/Process﹕ Sending signal. PID: 12164 SIG: 9
is this what you mean?
i think matches_Text is sometimes NULL?! how about adding an
if(matches_Text == null){
Log.v("Results","matches_Text is NULL!");
return;
}
add above code just after ArrayList<String> matches_Text = da...

Android IllegalStateException when recording audio on some devices

I want my program to record audio for 10 seconds and then stop and store my record in file storage, everything works fine on my Nexus 4 and Galaxy S 5, but when i test it in Galaxy S3 it crushes and raise error
10-02 02:13:44.942 1279-1279/com.taptester.tappapp E/AudioCaptureDemo﹕ prepare() failed
10-02 02:13:44.942 1279-1279/com.taptester.tappapp E/MediaRecorder﹕ start called in an invalid state: 4
10-02 02:13:44.942 1279-1279/com.taptester.tappapp D/AndroidRuntime﹕ Shutting down VM
10-02 02:13:44.942 1279-1279/com.taptester.tappapp W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xb1a12ba8)
10-02 02:13:44.952 1279-1279/com.taptester.tappapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.taptester.tappapp, PID: 1279
java.lang.IllegalStateException
at android.media.MediaRecorder.start(Native Method)
at com.taptester.tappapp.MainActivity.startRecording(MainActivity.java:203)
at com.taptester.tappapp.MainActivity.access$300(MainActivity.java:62)
at com.taptester.tappapp.MainActivity$6.onFinish(MainActivity.java:825)
at android.os.CountDownTimer$1.handleMessage(CountDownTimer.java:118)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
First i thought the error is in the file name, I'm declaring it like this:
public MainActivity() {
mFileName = Environment.getExternalStorageDirectory() + File.separator
+ Environment.DIRECTORY_DCIM + File.separator + "MyMemo.3gp";
//Environment.getExternalStorageDirectory().getAbsolutePath();
//mFileName += "/MyMemo.3gp";
}
Then i make a record like this:
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
try {
mRecorder.prepare();
mRecorder.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
Then i call the "StartRecording" method like this:
else if(command.equals("2")) {
startRecording();
Toast.makeText(getApplicationContext(), "Start recording...",
Toast.LENGTH_SHORT).show();
CountDownTimer start = new CountDownTimer(timer, 1000) {
#Override
public void onTick(long l) {
Toast.makeText(getApplicationContext(), "Recording!!!",
Toast.LENGTH_SHORT).show();
}
#Override
public void onFinish() {
stopRecording();
}
}.start();
you are not supposed to call mRecorder.start(); when mRecorder.prepare(); fails.
this is what caused the Illegal State Exception to be thrown.
Not all devices support all the encoding formats.
try changing these mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
and mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
change the format and Encoder to a file format and encoding format your s3 device supports.
for a start, change your encoding setting to default settings as follows and try if it works.
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);

Android SharedPreferences Multiple values in Multiple Activities

In my android application I used sharedpreference to store values in two activites like in first activity to store the values of login. So once user logs in, his username and password is saved and he will be routed to calculation activity, where user needs to fill his data inside several edittexts here I used second shared preference to store the edittext value. On pressing the show report button, user is directed to the next page that is daily prediction. So next time when user want to see the prediction, if he has logged in then he needs to skip the above said two activities and display the result. In my case I am able to achieve the login process correctly, but I used the second sharedpreference to store the edittext value the app is crashing. I am giving my code below.
first activity .. login activity
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.directcalc_xm);
/*
* Check if we successfully logged in before.
* If we did, redirect to calculation page
*/
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
if (settings.getString("logged", "").toString().equals("logged") && settings.getString("log", "").toString().equals("log"))
{
Intent intent = new Intent(DirectCalculation.this, FullExplanationEntry.class);
startActivity(intent);
}
else
{
btn1 = (Button) findViewById ( R.id.button1);
btn2 = (Button) findViewById ( R.id.button2);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(DirectCalculation.this, SignInActivity.class);
startActivity(intent);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent in = new Intent(DirectCalculation.this, SignUpActivity.class);
startActivity(in);
}
});
}
second Activity .. calculation page
if(firstName.equals(""))
{
Toast.makeText(getApplicationContext(), "First Name should not be left blank.. Please enter your First Name and try once again.", Toast.LENGTH_LONG).show();
return;
}
else if(lastName.equals(""))
{
Toast.makeText(getApplicationContext(), "Last Name should not be left blank.. Please enter your Last Name and try once again.", Toast.LENGTH_LONG).show();
return;
}
else if(callFirstName.equals(""))
{
Toast.makeText(getApplicationContext(), "Please enter your First Name that is currently used and try once again.", Toast.LENGTH_LONG).show();
return;
}
else
{
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("log", "log");
editor.commit();
Intent i = new Intent(this, TabLayoutActivity.class);
//Personal Year
i.putExtra("name18",sum18 + "");
//Personal Month
i.putExtra("name19",sum19 + "");
//Personal Dya
i.putExtra("name20",sum20 + "");
//Current Pinnacle
i.putExtra("pin", pin + "");
//Current Challenge
i.putExtra("ch", ch + "");
i.putExtra("yearstr", yearstr);
i.putExtra("monthstr", monthstr);
i.putExtra("daystr", daystr);
startActivity(i);
}
}
logcat
01-17 08:37:30.800: D/Single Product Details(1267): {"product":[{"updated_at":"0000-00-00 00:00:00","pyno":"4","pdyno":"4","pmnno":"4","pdaynumber":"This is the prediction for Personal Day Number 4.","pmonthnumber":"This is the prediction for Personal Month Number 4.","pyearnumber":"This is the prediction for Personal Year Number 4.","created_at":"2013-11-28 01:16:49","rthoughtnumber":"This is the prediction for Relational Thought Number 4.","pid":"4","rthno":"4"}],"success":1}
01-17 08:37:31.380: D/Single Product Details(1267): {"product":[{"pinnacle":"This is the prediction for Pinnacle Number 6.","created_at":"2013-11-23 03:08:57","pid":"6","updated_at":"0000-00-00 00:00:00","challenge":"This is the prediction for Challenge Number 6.","pinnum":"6","chnum":"6"}],"success":1}
01-17 08:37:31.461: I/Choreographer(1267): Skipped 37 frames! The application may be doing too much work on its main thread.
01-17 08:37:31.769: I/Choreographer(1267): Skipped 32 frames! The application may be doing too much work on its main thread.
01-17 08:37:32.130: I/Choreographer(1267): Skipped 69 frames! The application may be doing too much work on its main thread.
01-17 08:38:00.560: D/AndroidRuntime(1313): Shutting down VM
01-17 08:38:00.560: W/dalvikvm(1313): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
01-17 08:38:00.699: E/AndroidRuntime(1313): FATAL EXCEPTION: main
01-17 08:38:00.699: E/AndroidRuntime(1313): java.lang.RuntimeException: Unable to instantiate application android.app.Application: java.lang.NullPointerException
01-17 08:38:00.699: E/AndroidRuntime(1313): at android.app.LoadedApk.makeApplication(LoadedApk.java:504)
01-17 08:38:00.699: E/AndroidRuntime(1313): at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4364)
01-17 08:38:00.699: E/AndroidRuntime(1313): at android.app.ActivityThread.access$1300(ActivityThread.java:141)
01-17 08:38:00.699: E/AndroidRuntime(1313): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1294)
01-17 08:38:00.699: E/AndroidRuntime(1313): at android.os.Handler.dispatchMessage(Handler.java:99)
01-17 08:38:00.699: E/AndroidRuntime(1313): at android.os.Looper.loop(Looper.java:137)
01-17 08:38:00.699: E/AndroidRuntime(1313): at android.app.ActivityThread.main(ActivityThread.java:5041)
01-17 08:38:00.699: E/AndroidRuntime(1313): at java.lang.reflect.Method.invokeNative(Native Method)
01-17 08:38:00.699: E/AndroidRuntime(1313): at java.lang.reflect.Method.invoke(Method.java:511)
01-17 08:38:00.699: E/AndroidRuntime(1313): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-17 08:38:00.699: E/AndroidRuntime(1313): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-17 08:38:00.699: E/AndroidRuntime(1313): at dalvik.system.NativeStart.main(Native Method)
01-17 08:38:00.699: E/AndroidRuntime(1313): Caused by: java.lang.NullPointerException
01-17 08:38:00.699: E/AndroidRuntime(1313): at android.app.LoadedApk.initializeJavaContextClassLoader(LoadedApk.java:379)
01-17 08:38:00.699: E/AndroidRuntime(1313): at android.app.LoadedApk.getClassLoader(LoadedApk.java:322)
01-17 08:38:00.699: E/AndroidRuntime(1313): at android.app.LoadedApk.makeApplication(LoadedApk.java:496)
01-17 08:38:00.699: E/AndroidRuntime(1313): ... 11 more
SignIn Activity
if(password.equals(storedPassword))
{
Toast.makeText(SignInActivity.this, "Login Successfull", Toast.LENGTH_LONG).show();
/*
* So login information is correct,
* we will save the Preference data
* and redirect to the next activity.
*/
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("logged", "logged");
editor.commit();
// the data is verified correct and the activity id redirecting to the user details entry page.
Intent i = new Intent(SignInActivity.this,FullExplanationEntry.class);
startActivity(i);
}
and when pressing button I need to go to third activity that is TabLayoutActivity
You are on 4.0 right ? No fault of your part - see this issue and for a very nice explanation RuntimeException: Unable to instantiate application

Running out of Memory - bitmap size exceeds VM budget

I have searched a lot for a solution for my up and down buttons and can't seem to get anything working. When using the ImageButtons in the program, I am able to press three ImageButtons before I get OutOfMemoryError. Please any help will be great.
for(int i = 0; i < keys.length; i++)
{
keys[i].setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_DOWN)
{
for(int down = 0; down < keys.lenght; down++)
{
if(v == keys[down])
{
keys[down].keys[down].setImageResource(drawIDDOWN[down]);
keys[down].setAdjustViewBounds(true);
}
}
}
if(event.getAction() == MotionEvent.ACTION_UP)
{
for(int up = 0; up < keys.length; up++)
{
if(v == keys[up])
{
keys[up].setImageResource(drawIDUP[up]);
keys[up].setAdjustViewBounds(true);
}
}
}
return false;
}
});
}
Here is the LogCat:
threadid=1: thread exiting with uncaught exception
FATAL EXCEPTION: main
java.lang.OutOfMemoryError: bitmap size exceeds VM budget
android.graphics.Bitmap.nativeCreate(Native Method)
android.graphics.Bitmap.createBitmap(Bitmap.java:477)
android.graphics.Bitmap.createBitmap(Bitmap.java:444)
android.graphics.Bitmap.createScaledBitmap(Bitmap.java:349)
android.graphics.BitmapFactory.finishDecode(BitmapFactory.java:498)
android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:473)
android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:336)
android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:697)
android.content.res.Resources.loadDrawable(Resources.java:1709)
android.content.res.Resources.getDrawable(Resources.java:581)
android.widget.ImageView.resolveUri(ImageView.java:501)
android.widget.ImageView.setImageResource(ImageView.java:280)
f7kidzCalc.com.KidzCalcActivity$1.onTouch(KidzCalcActivity.java:253)
android.view.View.dispatchTouchEvent(View.java:3881)
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:942)
com.android.internal.policy.impl.PhoneWindow$DecorView.superDispatchTouchEvent
(PhoneWindow.java:1691)
com.android.internal.policy.impl.PhoneWindow.superDispatchTouchEvent
(PhoneWindow.java:1125)
android.app.Activity.dispatchTouchEvent(Activity.java:2096)
com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent
(PhoneWindow.java:1675)
android.view.ViewRoot.deliverPointerEvent(ViewRoot.java:2194)
android.view.ViewRoot.handleMessage(ViewRoot.java:1878)
android.os.Handler.dispatchMessage(Handler.java:99)
android.os.Looper.loop(Looper.java:123)
android.app.ActivityThread.main(ActivityThread.java:3683)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:507)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
dalvik.system.NativeStart.main(Native Method)
Is there an easy way to garbage collect, recycle images or just anything? I'm stuck..
Make sure you are not storing the activities or context in any other part of your program. This really messes with your memory management and causes lots of leaks.
You can send pointers to it using methods such as:
Good Form
public void doSomethingtoContext(Context c){
c.getApplicationContext()....//Variable 'c' only lasts for the length of the method
}
Bad Form
public static Context cOnText;
public void doSomethingtoContext(Context c){
cOnText = c; //DO NOT STORE THIS VALUE HERE
}
Basically, what I am trying to say is that, most of the times the image size aren't the problem, but instead something easy to overlook like this case.
Hope this helps.
Good luck!
Reduce the size of the image you are using. I had the exact problem. Image i was using was >500kB. Reduced size is around 50-60kB.

App Crashes on Launch, Trying to see if file exist's for login screen

I'm creating a Class that checks to see if the file has been created (Has username and passwords.) and if it does it creates an intent to go to another class to read the data and check it againts a server via FTP. For some reason, I can't get it to work, I've tried everything and read every single web page I could, but no luck.
My Code:
public class LogIn extends Activity implements OnClickListener {
Button send;
EditText user;
EditText pass;
CheckBox staySignedIn;
FileOutputStream Fos;
String a;
String b;
String string = a;
String string2 = b;
String FILENAME = "userandpass";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
send = (Button) findViewById(R.id.bLogIn);
user = (EditText) findViewById(R.id.eTuser);
pass = (EditText) findViewById(R.id.eTpassword);
staySignedIn = (CheckBox) findViewById(R.id.Cbstay);
send.setOnClickListener(this);
if (staySignedIn.isChecked()) {
String a = user.getText().toString();
String b = pass.getText().toString();
File f = new File(FILENAME);
try {
Fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
Fos.write(string.getBytes());
Fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
File file = getBaseContext().getFileStreamPath(FILENAME);
if(file.exists());
Intent i = new Intent(LogIn.this, ChatService.class);
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bLogIn:
if (pass.length() == 0)
Toast.makeText(this,
"Try to type in your username and password again!",
Toast.LENGTH_LONG).show();
else if (user.length() == 0)
Toast.makeText(this,
"Try to type in your username and password again!",
Toast.LENGTH_LONG).show();
else {
String u = user.getText().toString();
String p = pass.getText().toString();
Bundle send = new Bundle();
send.putString("key", u);
send.putString("key1", p);
Intent a = new Intent(LogIn.this, logincheck.class);
a.putExtra("key", u);
a.putExtra("key1", p);
startActivity(a);
Toast.makeText(this, "Were signing you in!", Toast.LENGTH_LONG)
.show();
break;
}
}
}
}
LogCat:
01-19 11:37:17.601: W/dalvikvm(4411): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
01-19 11:37:17.621: E/AndroidRuntime(4411): FATAL EXCEPTION: main
01-19 11:37:17.621: E/AndroidRuntime(4411): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gta5news.bananaphone/com.gta5news.bananaphone.LogIn}: java.lang.NullPointerException
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.os.Handler.dispatchMessage(Handler.java:99)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.os.Looper.loop(Looper.java:123)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread.main(ActivityThread.java:4627)
01-19 11:37:17.621: E/AndroidRuntime(4411): at java.lang.reflect.Method.invokeNative(Native Method)
01-19 11:37:17.621: E/AndroidRuntime(4411): at java.lang.reflect.Method.invoke(Method.java:521)
01-19 11:37:17.621: E/AndroidRuntime(4411): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-19 11:37:17.621: E/AndroidRuntime(4411): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-19 11:37:17.621: E/AndroidRuntime(4411):
at dalvik.system.NativeStart.main(Native Method)
01-19 11:37:17.621: E/AndroidRuntime(4411): Caused by: java.lang.NullPointerException
01-19 11:37:17.621: E/AndroidRuntime(4411): at com.gta5news.bananaphone.LogIn.onCreate(LogIn.java:55)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-19 11:37:17.621: E/AndroidRuntime(4411): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
If line 55 is
Fos.write(string.getBytes());
then either Fos or string is uninitialized. Given that string is initialized to a which is itself uninitialized, that explains it. You need to assign a proper value to string.
Fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
It seems for some reason openFileOutput returning null which makes Fos null, which is throwing NullPointerException.
Add
if(Fos != null) {
Fos.write(string.getBytes());
Fos.close();
} check.
OR catch NullpointerException.

Categories

Resources