Hiding Keyboard on Android crashes app - java

When I try to run this line in order to hide the keyboard (I get the InputMethodManager):
this.context = context;
InputMethodManager mgr = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); //this line crashes the app
What should I do to fix it?
(I am running it from a fragment by the way)
Crash Log:
11-03 16:20:26.700: D/AndroidRuntime(2809): Shutting down VM
11-03 16:20:26.700: W/dalvikvm(2809): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
11-03 16:20:26.710: E/AndroidRuntime(2809): FATAL EXCEPTION: main
11-03 16:20:26.710: E/AndroidRuntime(2809): java.lang.NullPointerException
11-03 16:20:26.710: E/AndroidRuntime(2809): at co.emuze.tabtest1.Tab1$1.onClick(Tab1.java:32)
11-03 16:20:26.710: E/AndroidRuntime(2809): at android.view.View.performClick(View.java:4084)
11-03 16:20:26.710: E/AndroidRuntime(2809): at android.view.View$PerformClick.run(View.java:16966)
11-03 16:20:26.710: E/AndroidRuntime(2809): at android.os.Handler.handleCallback(Handler.java:615)
11-03 16:20:26.710: E/AndroidRuntime(2809): at android.os.Handler.dispatchMessage(Handler.java:92)
11-03 16:20:26.710: E/AndroidRuntime(2809): at android.os.Looper.loop(Looper.java:137)
11-03 16:20:26.710: E/AndroidRuntime(2809): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-03 16:20:26.710: E/AndroidRuntime(2809): at java.lang.reflect.Method.invokeNative(Native Method)
11-03 16:20:26.710: E/AndroidRuntime(2809): at java.lang.reflect.Method.invoke(Method.java:511)
11-03 16:20:26.710: E/AndroidRuntime(2809): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-03 16:20:26.710: E/AndroidRuntime(2809): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-03 16:20:26.710: E/AndroidRuntime(2809): at dalvik.system.NativeStart.main(Native Method)
Full on click method:
public void onClick(View v) {
text1.setText(editText1.getText().toString());
InputMethodManager mgr = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(editText1.getWindowToken(), 0);
}

It would appear context is null - you show the line this.context = context, and if the right hand side context is not a variable local to that method you're doing nothing. I think what you may be looking for is context = getApplicationContext()

Dont forget to use try catch blog because in case when your keyboard not open and if you use key key board hide code app crashed
User below code in Fragment
try {
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
} catch (Exception e) {
// TODO: handle exception
}

Related

NullPointerException on MrNom

I was trying to execute Mr Nom(from the book Begining Android Games by Mario Zechner). but it doesn't work. My first atemp was create 2 different projects, one called framework where are com.badlogic.androidgames.framework and com.badlogic.androidgames.framework files and other project called mrnom (com.badlogic.androidgames.mrnom)with the rest of files. the framework project was added mrnom project/java build path/project/add and the result was this:
logcat
11-07 15:21:55.573: W/dalvikvm(641): Unable to resolve superclass of Lcom/badlogic/androidgames/mrnom/MrNom; (445)
11-07 15:21:55.573: W/dalvikvm(641): Link of class 'Lcom/badlogic/androidgames/mrnom/MrNom;' failed
11-07 15:21:55.573: D/AndroidRuntime(641): Shutting down VM
11-07 15:21:55.573: W/dalvikvm(641): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
11-07 15:21:55.583: E/AndroidRuntime(641): FATAL EXCEPTION: main
11-07 15:21:55.583: E/AndroidRuntime(641): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.badlogic.androidgames.mrnom/com.badlogic.androidgames.mrnom.MrNom}: java.lang.ClassNotFoundException: com.badlogic.androidgames.mrnom.MrNom
11-07 15:21:55.583: E/AndroidRuntime(641): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.app.ActivityThread.access$600(ActivityThread.java:130)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.os.Handler.dispatchMessage(Handler.java:99)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.os.Looper.loop(Looper.java:137)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-07 15:21:55.583: E/AndroidRuntime(641): at java.lang.reflect.Method.invokeNative(Native Method)
11-07 15:21:55.583: E/AndroidRuntime(641): at java.lang.reflect.Method.invoke(Method.java:511)
11-07 15:21:55.583: E/AndroidRuntime(641): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-07 15:21:55.583: E/AndroidRuntime(641): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-07 15:21:55.583: E/AndroidRuntime(641): at dalvik.system.NativeStart.main(Native Method)
11-07 15:21:55.583: E/AndroidRuntime(641): Caused by: java.lang.ClassNotFoundException: com.badlogic.androidgames.mrnom.MrNom
11-07 15:21:55.583: E/AndroidRuntime(641): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
11-07 15:21:55.583: E/AndroidRuntime(641): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
11-07 15:21:55.583: E/AndroidRuntime(641): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
11-07 15:21:55.583: E/AndroidRuntime(641): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
11-07 15:21:55.583: E/AndroidRuntime(641): ... 11 more
11-07 15:24:06.602: E/Trace(662): error opening trace file: No such file or directory (2)
11-07 15:24:06.902: W/dalvikvm(662): Unable to resolve superclass of Lcom/badlogic/androidgames/mrnom/MrNom; (445)
11-07 15:24:06.902: W/dalvikvm(662): Link of class 'Lcom/badlogic/androidgames/mrnom/MrNom;' failed
11-07 15:24:06.902: D/AndroidRuntime(662): Shutting down VM
11-07 15:24:06.932: W/dalvikvm(662): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
11-07 15:24:06.952: E/AndroidRuntime(662): FATAL EXCEPTION: main
11-07 15:24:06.952: E/AndroidRuntime(662): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.badlogic.androidgames.mrnom/com.badlogic.androidgames.mrnom.MrNom}: java.lang.ClassNotFoundException: com.badlogic.androidgames.mrnom.MrNom
11-07 15:24:06.952: E/AndroidRuntime(662): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.app.ActivityThread.access$600(ActivityThread.java:130)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.os.Handler.dispatchMessage(Handler.java:99)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.os.Looper.loop(Looper.java:137)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.app.ActivityThread.main(ActivityThread.java:4745)
11-07 15:24:06.952: E/AndroidRuntime(662): at java.lang.reflect.Method.invokeNative(Native Method)
11-07 15:24:06.952: E/AndroidRuntime(662): at java.lang.reflect.Method.invoke(Method.java:511)
11-07 15:24:06.952: E/AndroidRuntime(662): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-07 15:24:06.952: E/AndroidRuntime(662): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-07 15:24:06.952: E/AndroidRuntime(662): at dalvik.system.NativeStart.main(Native Method)
11-07 15:24:06.952: E/AndroidRuntime(662): Caused by: java.lang.ClassNotFoundException: com.badlogic.androidgames.mrnom.MrNom
11-07 15:24:06.952: E/AndroidRuntime(662): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61)
11-07 15:24:06.952: E/AndroidRuntime(662): at java.lang.ClassLoader.loadClass(ClassLoader.java:501)
11-07 15:24:06.952: E/AndroidRuntime(662): at java.lang.ClassLoader.loadClass(ClassLoader.java:461)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
11-07 15:24:06.952: E/AndroidRuntime(662): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
11-07 15:24:06.952: E/AndroidRuntime(662): ... 11 more
later I removed the framework from mrnom and added it using a jar file, the result was the same
Now, I copy the com.badlogic.androidgames.framework and com.badlogic.androidgames.framework files into mr project then I have com.badlogic.androidgames.mrnom, com.badlogic.androidgames.framework and com.badlogic.androidgames.framework in the same project but now the error is
logcat
12-05 15:42:43.510: D/dalvikvm(582): GC_EXTERNAL_ALLOC freed 57K, 53% free 2569K/5379K, external 1925K/2137K, paused 239ms
12-05 15:42:43.860: D/dalvikvm(582): GC_EXTERNAL_ALLOC freed 3K, 53% free 2569K/5379K, external 2515K/2701K, paused 36ms
12-05 15:42:44.100: W/dalvikvm(582): threadid=11: thread exiting with uncaught exception (group=0x40015560)
12-05 15:42:44.100: E/AndroidRuntime(582): FATAL EXCEPTION: Thread-12
12-05 15:42:44.100: E/AndroidRuntime(582): java.lang.NullPointerException
12-05 15:42:44.100: E/AndroidRuntime(582): at com.badlogic.androidgames.mrnom.Settings.load(Settings.java:18)
12-05 15:42:44.100: E/AndroidRuntime(582): at com.badlogic.androidgames.mrnom.LoadingScreen.update(LoadingScreen.java:41)
12-05 15:42:44.100: E/AndroidRuntime(582): at com.badlogic.androidgames.framework.impl.AndroidFastRenderView.run(AndroidFastRenderView.java:36)
12-05 15:42:44.100: E/AndroidRuntime(582): at java.lang.Thread.run(Thread.java:1019)
Settings
package com.badlogic.androidgames.mrnom;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import com.balogic.androidgames.framework.FileIO;
public class Settings {
public static boolean soundEnable=true;
public static int[] highscores=new int[]{100,80,50,30,10};
public static void load(FileIO files){
BufferedReader in=null;
try{
in=new BufferedReader(new InputStreamReader(files.readFile(".mrnom")));// line 18 error here
soundEnable=Boolean.parseBoolean(in.readLine());
for(int i=0; i<5;i++){
highscores[i]=Integer.parseInt(in.readLine());
}
}catch(IOException e){
// :( vale,trabajamos con valores predeterminados
}catch(NumberFormatException e){
// :/ vale, estos valores nos han salvado el día
}finally{
try{
if(in!=null)
in.close();
}catch(IOException e){
//nada
}
}
}
public static void save(FileIO files){
BufferedWriter out=null;
try{
out=new BufferedWriter(new OutputStreamWriter(files.writeFile(".mrnom")));
out.write(Boolean.toString(soundEnable));
for(int i=0; i<5; i++){
out.write(Integer.toString(highscores[i]));
}
}catch(IOException e){
//nada
}finally{
try{
if(out!=null)
out.close();
}catch(IOException e){
//nada
}
}
}
public static void addScore(int score){
for(int i=0;i<5;i++){
if(highscores[i]<score){
for(int j=4;j>i;j--)
highscores[j]=highscores[j-1];
highscores[i]=score;
break;
}
}
}
}
Loadingsceen
package com.badlogic.androidgames.mrnom;
import com.badlogic.androidgames.framework.Game;
import com.badlogic.androidgames.framework.Graphics;
import com.badlogic.androidgames.framework.Graphics.PixmapFormat;
import com.badlogic.androidgames.framework.Screen;
public class LoadingScreen extends Screen{
public LoadingScreen(Game game){
super(game);
}
#Override
public void update(float deltaTime){
Graphics g=game.getGraphics();
Assets.background = g.newPixmap("background.png", PixmapFormat.RGB565);
Assets.logo = g.newPixmap("logo.png", PixmapFormat.ARGB4444);
Assets.mainMenu = g.newPixmap("mainmenu.png", PixmapFormat.ARGB4444);
Assets.buttons = g.newPixmap("buttons.png", PixmapFormat.ARGB4444);
Assets.help1 = g.newPixmap("help1.png", PixmapFormat.ARGB4444);
Assets.help2 = g.newPixmap("help2.png", PixmapFormat.ARGB4444);
Assets.help3 = g.newPixmap("help3.png", PixmapFormat.ARGB4444);
Assets.numbers = g.newPixmap("numbers.png", PixmapFormat.ARGB4444);
Assets.ready = g.newPixmap("ready.png", PixmapFormat.ARGB4444);
Assets.pause = g.newPixmap("pausemenu.png", PixmapFormat.ARGB4444);
Assets.gameOver = g.newPixmap("gameover.png", PixmapFormat.ARGB4444);
Assets.headUp = g.newPixmap("headup.png", PixmapFormat.ARGB4444);
Assets.headLeft = g.newPixmap("headleft.png", PixmapFormat.ARGB4444);
Assets.headDown = g.newPixmap("headdown.png", PixmapFormat.ARGB4444);
Assets.headRight = g.newPixmap("headright.png", PixmapFormat.ARGB4444);
Assets.tail = g.newPixmap("tail.png", PixmapFormat.ARGB4444);
Assets.stain1 = g.newPixmap("stain.png", PixmapFormat.ARGB4444);
Assets.stain2 = g.newPixmap("stain2.png", PixmapFormat.ARGB4444);
Assets.stain3 = g.newPixmap("stain3.png", PixmapFormat.ARGB4444);
Assets.click = game.getAudio().newSound("click.ogg");
Assets.eat = game.getAudio().newSound("eat.ogg");
Assets.bitten = game.getAudio().newSound("bitten.ogg");
Settings.load(game.getFileIO()); //line 41 error here
game.setScreen(new MainMenuScreen(game));
}
#Override
public void present(float deltaTime) {
// TODO Auto-generated method stub
}
#Override
public void pause() {
// TODO Auto-generated method stub
}
#Override
public void resume() {
// TODO Auto-generated method stub
}
#Override
public void dispose() {
// TODO Auto-generated method stub
}
}
AndroidFastRenderView
package com.badlogic.androidgames.framework.impl;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class AndroidFastRenderView extends SurfaceView implements Runnable{
AndroidGame game;
Bitmap framebuffer;
Thread renderThread=null;
SurfaceHolder holder;
volatile boolean running=false;
public AndroidFastRenderView(AndroidGame game,Bitmap framebuffer){
super(game);
this.game=game;
this.framebuffer=framebuffer;
this.holder=getHolder();
}
public void resume(){
running=true;
renderThread=new Thread(this);
renderThread.start();
}
public void run(){
Rect dstRect=new Rect();
long startTime=System.nanoTime();
while(running){
if(!holder.getSurface().isValid())
continue;
float deltaTime=(System.nanoTime()-startTime)/1000000000.0f;
startTime=System.nanoTime();
game.getCurrentScreen().update(deltaTime);//line 36 error here
game.getCurrentScreen().present(deltaTime);
Canvas canvas=holder.lockCanvas();
canvas.getClipBounds(dstRect);
canvas.drawBitmap(framebuffer, null, dstRect,null);
holder.unlockCanvasAndPost(canvas);
}
}
public void pause(){
running=false;
while(true){
try{
renderThread.join();
break;
}catch(InterruptedException e){
//vuelve a intentarlo
}
}
}
}
Eclipse doesn't showme any mistake on code but on the emulator just say "Sorry! the application mrnom (process com.badlogic.androidgames.mrnom) has stopped unexpectedly. Please try again"
Can you help me with this? No idea what's happening :( Thank you so much.

java.lang NULL POINT Exception [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
It say there's error in line 71 but i could figure what error was it any kind souls willing to help me ? THANKS
my problem is that when i click on the foodbutton on the mainactivity , the system crashes. BUT the logcat shows the error in food.java which is another page.
Here's the coding !
package com.yiqiexample.cabincrew;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
//import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class Food extends ListActivity
implements OnClickListener {
// Progress Dialog
private ProgressDialog pDialog;
//testing on Emulator:
private static final String READ_COMMENTS_URL = "http://10.0.2.2/pbda2/foodordered.php";
// private CheckBox chkFood, chkDrinks, chkServices;
//private Button btnDisplay, chkClear, deliever, chkClearFood, fooddeliever, drinksdeliever, servicesdeliever, chkClearDrinks, chkClearServices;
//private TextView clearThis,orderdisplay, clearThisFood, foodorderdisplay, drinksorderdisplay, servicesorderdisplay, clearThisDrinks, clearThisServices;
private static final String TAG_SUCCESS = "success";
private static final String TAG_POSTS = "posts";
private static final String TAG_SEATNUMBER = "seatnumber";
private static final String TAG_FOODORDERED = "foodordered";
//it's important to note that the message is both in the parent branch of
//our JSON tree that displays a "Post Available" or a "No Post Available" message,
//and there is also a message for each individual post, listed under the "posts"
//category, that displays what the user typed as their message.
//An array of all of our comments
private JSONArray mComments = null;
//manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mCommentList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.food);
View v = findViewById(R.id.backmain);
//set event listener
v.setOnClickListener(this);
View z = findViewById(R.id.drinksbtn);
//set event listener
z.setOnClickListener(this);
View x = findViewById(R.id.servicebtn);
//set event listener
x.setOnClickListener(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//loading the comments via AsyncTask
new LoadComments().execute();
}
/**
* Retrieves recent post data from the server.
*/
public void updateJSONdata() {
// Instantiate the arraylist to contain all the JSON data.
// we are going to use a bunch of key-value pairs, referring
// to the json element name, and the content, for example,
// message it the tag, and "I'm awesome" as the content..
mCommentList = new ArrayList<HashMap<String, String>>();
// Bro, it's time to power up the J parser
JSONParser jParser = new JSONParser();
// Feed the beast our comments url, and it spits us
//back a JSON object. Boo-yeah Jerome.
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
//when parsing JSON stuff, we should probably
//try to catch any exceptions:
try {
//I know I said we would check if "Posts were Avail." (success==1)
//before we tried to read the individual posts, but I lied...
//mComments will tell us how many "posts" or comments are
//available
mComments = json.getJSONArray(TAG_POSTS);
// looping through all posts according to the json object returned
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
//gets the content of each tag
String seatnumber = c.getString(TAG_SEATNUMBER);
String foodordered = c.getString(TAG_FOODORDERED);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_SEATNUMBER, seatnumber);
map.put(TAG_FOODORDERED, foodordered);
// adding HashList to ArrayList
mCommentList.add(map);
//annndddd, our JSON data is up to date same with our array list
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onClick(View arg0) {
if(arg0.getId() == R.id.backmain){
//define a new Intent for the second Activity
Intent intent = new Intent(this,MainActivity.class);
//start the second Activity
this.startActivity(intent);
}
if(arg0.getId() == R.id.drinksbtn){
//define a new Intent for the second Activity
Intent intent = new Intent(this,Drinks.class);
//start the second Activity
this.startActivity(intent);
}
if(arg0.getId() == R.id.servicebtn){
//define a new Intent for the second Activity
Intent intent = new Intent(this,Services.class);
//start the second Activity
this.startActivity(intent);
}
}
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
// For a ListActivity we need to set the List Adapter, and in order to do
//that, we need to create a ListAdapter. This SimpleAdapter,
//will utilize our updated Hashmapped ArrayList,
//use our single_post xml template for each item in our list,
//and place the appropriate info from the list to the
//correct GUI id. Order is important here.
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.single_post, new String[] { TAG_SEATNUMBER, TAG_FOODORDERED
//TAG_DRINKSORDERED, TAG_SERVICES
}, new int[] { R.id.seatnumber, R.id.orders
//R.id.drinkstv, R.id.servicestv,
});
// I shouldn't have to comment on this one:
setListAdapter(adapter);
// Optional: when the user clicks a list item we
//could do something. However, we will choose
//to do nothing...
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// This method is triggered if an item is click within our
// list. For our example we won't be using this, but
// it is useful to know in real life applications.
}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Food.this);
pDialog.setMessage("Loading orders...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
//we will develop this method in version 2
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
//we will develop this method in version 2
updateList();
}
}
}
Here's the coding for main page
package com.yiqiexample.cabincrew;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity
implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View v = findViewById(R.id.foodbutton);
//set event listener
v.setOnClickListener(this);
View x= findViewById(R.id.drinks);
//set event listener
x.setOnClickListener(this);
View y = findViewById(R.id.services);
//set event listener
y.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
if(arg0.getId() == R.id.foodbutton){
//define a new Intent for the second Activity
Intent intent = new Intent(this,Food.class);
//start the second Activity
this.startActivity(intent);
}
if(arg0.getId() == R.id.drinks){
//define a new Intent for the second Activity
Intent intent = new Intent(this,Drinks.class);
//start the second Activity
this.startActivity(intent);
}
if(arg0.getId() == R.id.services){
//define a new Intent for the second Activity
Intent intent = new Intent(this,Services.class);
//start the second Activity
this.startActivity(intent);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
food.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android1="http://schemas.android.com/apk/res/android"
android1:id="#+id/bg2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android1:background="#E0FFFF" >
<Button
android1:id="#+id/backmain"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_alignParentBottom="true"
android1:layout_alignParentRight="true"
android1:text="#string/backtomain" />
<Button
android1:id="#+id/servicesdelivered"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_above="#+id/foodbtn"
android1:layout_alignLeft="#+id/backmain"
android1:text="#string/servicesdelivered"
android1:visibility="invisible" />
<Button
android:id="#+id/servicebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="358dp"
android:layout_toRightOf="#+id/foodbutton"
android:text="SERVICES" />
<Button
android1:id="#+id/foodbtn"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_alignParentBottom="true"
android1:layout_marginBottom="23dp"
android1:layout_marginRight="24dp"
android1:text="DRINKS ORDERS" />
<LinearLayout
android:id="#+id/top_layover"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="horizontal" >
<TextView
android1:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="#string/foodtitle"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/top_layover"
android1:layout_alignBottom="#+id/servicesdelivered"
android:background="#fff"
android:divider="#android:color/transparent"
android:scrollbars="none" />
<LinearLayout
android:id="#+id/bottom_layover"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:orientation="horizontal"
android:weightSum="2" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Here's the LOGCAT !
11-03 04:23:36.974: W/dalvikvm(756): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-03 04:23:37.093: E/AndroidRuntime(756): FATAL EXCEPTION: main
11-03 04:23:37.093: E/AndroidRuntime(756): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.yiqiexample.cabincrew/com.yiqiexample.cabincrew.Food}: java.lang.NullPointerException
11-03 04:23:37.093: E/AndroidRuntime(756): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-03 04:23:37.093: E/AndroidRuntime(756): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-03 04:23:37.093: E/AndroidRuntime(756): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-03 04:23:37.093: E/AndroidRuntime(756): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-03 04:23:37.093: E/AndroidRuntime(756): at android.os.Handler.dispatchMessage(Handler.java:99)
11-03 04:23:37.093: E/AndroidRuntime(756): at android.os.Looper.loop(Looper.java:137)
11-03 04:23:37.093: E/AndroidRuntime(756): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-03 04:23:37.093: E/AndroidRuntime(756): at java.lang.reflect.Method.invokeNative(Native Method)
11-03 04:23:37.093: E/AndroidRuntime(756): at java.lang.reflect.Method.invoke(Method.java:525)
11-03 04:23:37.093: E/AndroidRuntime(756): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-03 04:23:37.093: E/AndroidRuntime(756): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-03 04:23:37.093: E/AndroidRuntime(756): at dalvik.system.NativeStart.main(Native Method)
11-03 04:23:37.093: E/AndroidRuntime(756): Caused by: java.lang.NullPointerException
11-03 04:23:37.093: E/AndroidRuntime(756): at com.yiqiexample.cabincrew.Food.onCreate(Food.java:71)
11-03 04:23:37.093: E/AndroidRuntime(756): at android.app.Activity.performCreate(Activity.java:5133)
11-03 04:23:37.093: E/AndroidRuntime(756): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-03 04:23:37.093: E/AndroidRuntime(756): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-03 04:23:37.093: E/AndroidRuntime(756): ... 11 more
11-03 04:23:43.713: I/Process(756): Sending signal. PID: 756 SIG: 9
11-03 04:23:46.715: D/dalvikvm(895): GC_FOR_ALLOC freed 44K, 4% free 2600K/2708K, paused 57ms, total 60ms
11-03 04:23:46.753: I/dalvikvm-heap(895): Grow heap (frag case) to 4.941MB for 2457616-byte allocation
11-03 04:23:46.893: D/dalvikvm(895): GC_FOR_ALLOC freed 2K, 3% free 4998K/5112K, paused 130ms, total 130ms
11-03 04:23:47.793: D/gralloc_goldfish(895): Emulator without GPU emulation detected.
11-03 04:31:41.842: I/Choreographer(895): Skipped 125 frames! The application may be doing too much work on its main thread.
11-03 04:31:42.284: I/Choreographer(895): Skipped 62 frames! The application may be doing too much work on its main thread.
11-03 04:31:42.913: I/Choreographer(895): Skipped 71 frames! The application may be doing too much work on its main thread.
11-03 04:32:15.008: D/dalvikvm(895): GC_FOR_ALLOC freed 143K, 4% free 5688K/5892K, paused 138ms, total 186ms
11-03 04:32:16.063: I/Choreographer(895): Skipped 91 frames! The application may be doing too much work on its main thread.
11-03 04:32:16.603: I/Choreographer(895): Skipped 58 frames! The application may be doing too much work on its main thread.
11-03 04:32:42.023: I/Choreographer(895): Skipped 46 frames! The application may be doing too much work on its main thread.
11-03 04:32:44.223: I/Choreographer(895): Skipped 30 frames! The application may be doing too much work on its main thread.
11-03 04:32:45.053: I/Choreographer(895): Skipped 122 frames! The application may be doing too much work on its main thread.
11-03 04:32:45.513: I/Choreographer(895): Skipped 68 frames! The application may be doing too much work on its main thread.
11-03 04:32:46.555: I/Choreographer(895): Skipped 135 frames! The application may be doing too much work on its main thread.
11-03 04:32:49.742: D/dalvikvm(895): GC_FOR_ALLOC freed 152K, 4% free 6327K/6544K, paused 350ms, total 378ms
11-03 04:32:50.245: D/dalvikvm(895): GC_FOR_ALLOC freed 59K, 4% free 7253K/7540K, paused 187ms, total 190ms
11-03 04:32:50.349: I/Choreographer(895): Skipped 192 frames! The application may be doing too much work on its main thread.
11-03 04:32:54.232: I/Choreographer(895): Skipped 35 frames! The application may be doing too much work on its main thread.
11-03 04:32:54.702: I/Choreographer(895): Skipped 73 frames! The application may be doing too much work on its main thread.
11-03 04:32:55.134: I/Choreographer(895): Skipped 71 frames! The application may be doing too much work on its main thread.
11-03 04:32:55.968: I/Choreographer(895): Skipped 112 frames! The application may be doing too much work on its main thread.
11-03 04:32:59.177: D/dalvikvm(895): GC_FOR_ALLOC freed 1715K, 21% free 6795K/8580K, paused 279ms, total 332ms
11-03 04:32:59.322: I/Choreographer(895): Skipped 134 frames! The application may be doing too much work on its main thread.
11-03 04:33:03.003: I/Choreographer(895): Skipped 53 frames! The application may be doing too much work on its main thread.
11-03 04:33:04.183: I/Choreographer(895): Skipped 35 frames! The application may be doing too much work on its main thread.
11-03 04:33:04.643: I/Choreographer(895): Skipped 35 frames! The application may be doing too much work on its main thread.
11-03 04:33:08.103: I/Choreographer(895): Skipped 43 frames! The application may be doing too much work on its main thread.
11-03 04:34:58.453: D/AndroidRuntime(951): Shutting down VM
11-03 04:34:58.453: W/dalvikvm(951): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-03 04:34:58.464: E/AndroidRuntime(951): FATAL EXCEPTION: main
11-03 04:34:58.464: E/AndroidRuntime(951): java.lang.RuntimeException: Unable to instantiate application android.app.Application: java.lang.IllegalStateException: Unable to get package info for com.yiqiexample.cabincrew; is package not installed?
11-03 04:34:58.464: E/AndroidRuntime(951): at android.app.LoadedApk.makeApplication(LoadedApk.java:509)
11-03 04:34:58.464: E/AndroidRuntime(951): at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4417)
11-03 04:34:58.464: E/AndroidRuntime(951): at android.app.ActivityThread.access$1300(ActivityThread.java:141)
11-03 04:34:58.464: E/AndroidRuntime(951): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
11-03 04:34:58.464: E/AndroidRuntime(951): at android.os.Handler.dispatchMessage(Handler.java:99)
11-03 04:34:58.464: E/AndroidRuntime(951): at android.os.Looper.loop(Looper.java:137)
11-03 04:34:58.464: E/AndroidRuntime(951): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-03 04:34:58.464: E/AndroidRuntime(951): at java.lang.reflect.Method.invokeNative(Native Method)
11-03 04:34:58.464: E/AndroidRuntime(951): at java.lang.reflect.Method.invoke(Method.java:525)
11-03 04:34:58.464: E/AndroidRuntime(951): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-03 04:34:58.464: E/AndroidRuntime(951): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-03 04:34:58.464: E/AndroidRuntime(951): at dalvik.system.NativeStart.main(Native Method)
11-03 04:34:58.464: E/AndroidRuntime(951): Caused by: java.lang.IllegalStateException: Unable to get package info for com.yiqiexample.cabincrew; is package not installed?
11-03 04:34:58.464: E/AndroidRuntime(951): at android.app.LoadedApk.initializeJavaContextClassLoader(LoadedApk.java:369)
11-03 04:34:58.464: E/AndroidRuntime(951): at android.app.LoadedApk.getClassLoader(LoadedApk.java:322)
11-03 04:34:58.464: E/AndroidRuntime(951): at android.app.LoadedApk.makeApplication(LoadedApk.java:501)
11-03 04:34:58.464: E/AndroidRuntime(951): ... 11 more
11-03 04:35:10.544: D/dalvikvm(994): GC_FOR_ALLOC freed 55K, 5% free 2600K/2720K, paused 30ms, total 33ms
11-03 04:35:10.562: I/dalvikvm-heap(994): Grow heap (frag case) to 4.940MB for 2457616-byte allocation
11-03 04:35:10.673: D/dalvikvm(994): GC_FOR_ALLOC freed 2K, 3% free 4998K/5124K, paused 110ms, total 110ms
11-03 04:35:11.213: D/gralloc_goldfish(994): Emulator without GPU emulation detected.
11-03 04:40:44.032: D/AndroidRuntime(994): Shutting down VM
11-03 04:40:44.042: W/dalvikvm(994): threadid=1: thread exiting with uncaught exception (group=0x41465700)
11-03 04:40:44.112: E/AndroidRuntime(994): FATAL EXCEPTION: main
11-03 04:40:44.112: E/AndroidRuntime(994): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.yiqiexample.cabincrew/com.yiqiexample.cabincrew.Food}: java.lang.NullPointerException
11-03 04:40:44.112: E/AndroidRuntime(994): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
11-03 04:40:44.112: E/AndroidRuntime(994): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
11-03 04:40:44.112: E/AndroidRuntime(994): at android.app.ActivityThread.access$600(ActivityThread.java:141)
11-03 04:40:44.112: E/AndroidRuntime(994): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
11-03 04:40:44.112: E/AndroidRuntime(994): at android.os.Handler.dispatchMessage(Handler.java:99)
11-03 04:40:44.112: E/AndroidRuntime(994): at android.os.Looper.loop(Looper.java:137)
11-03 04:40:44.112: E/AndroidRuntime(994): at android.app.ActivityThread.main(ActivityThread.java:5103)
11-03 04:40:44.112: E/AndroidRuntime(994): at java.lang.reflect.Method.invokeNative(Native Method)
11-03 04:40:44.112: E/AndroidRuntime(994): at java.lang.reflect.Method.invoke(Method.java:525)
11-03 04:40:44.112: E/AndroidRuntime(994): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
11-03 04:40:44.112: E/AndroidRuntime(994): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-03 04:40:44.112: E/AndroidRuntime(994): at dalvik.system.NativeStart.main(Native Method)
11-03 04:40:44.112: E/AndroidRuntime(994): Caused by: java.lang.NullPointerException
11-03 04:40:44.112: E/AndroidRuntime(994): at com.yiqiexample.cabincrew.Food.onCreate(Food.java:71)
11-03 04:40:44.112: E/AndroidRuntime(994): at android.app.Activity.performCreate(Activity.java:5133)
11-03 04:40:44.112: E/AndroidRuntime(994): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-03 04:40:44.112: E/AndroidRuntime(994): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
11-03 04:40:44.112: E/AndroidRuntime(994): ... 11 more
if you need more coding to spot the error please tell me ! :)
Assuming line 71 is this one.-
z.setOnClickListener(this);
this line must be setting z to null.
View z = findViewById(R.id.drinksbtn);
Double check that food layout contains a view with id drinksbtn with no typos.
Notice that there's no drinksbtn in your xml, nor foodbutton neither.

Spinner problems with Sharedpreferences

Sorry,this is my first time to put questions in this site
My Function: I set two Buttons to restore and save the information in the Spinner and EditText with the function Sharedpreferences.
I execute the program at the first time. The program will appear the error state,if I click the Button "restore" to restore the information in Spinner. But I haven't met the problem when I restore the information in EditText.
This is the code in Spinner
private Spinner.OnItemSelectedListener getfeet = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
feet_out = parent.getSelectedItemPosition() + 2;
select_f = feet.getSelectedItemPosition(); //save the position you choose
Toast.makeText(MainActivity.this,
"you chose " + parent.getSelectedItem().toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
};
private Spinner.OnItemSelectedListener getinch = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
inch_out = parent.getSelectedItemPosition();
select_i = inch.getSelectedItemPosition(); //save the position you choose
Toast.makeText(MainActivity.this,
"you chose " + parent.getSelectedItem().toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
};
This is the code which executes the function of save in Sharedpreferences
private void save_() {
settings = getSharedPreferences("DATA", 0);
settings.edit().putInt("DATA_FEET", select_f) //store the position in DATA_FEET and DATA_INCH
.putInt("DATA_INCH", select_i)
.putString("DATA_WEIGHT", weight.getText().toString()).commit();
Toast.makeText(MainActivity.this, R.string.done, Toast.LENGTH_SHORT) //save done
.show();
}
This is the code which executes the function of restore in Sharedpreferences
private void restore_() {
feet.setSelection(settings.getInt("DATA_FEET", select_f)); //restore the position
inch.setSelection(settings.getInt("DATA_INCH", select_i));
weight.setText(settings.getString("DATA_WEIGHT", "EMPTY"));
}
My problem is that I can't use the function of restore at the program executing at the first time. Is there any solution to solve the problem?? Because it is normal in EditText,but it is abnormal in Spinner. Thanks :))
This is the state. :))
10-23 23:14:11.677: D/TextLayoutCache(26370): Using debug level: 0 - Debug Enabled: 0
10-23 23:14:11.747: D/libEGL(26370): loaded /system/lib/egl/libGLES_android.so
10-23 23:14:11.797: D/libEGL(26370): loaded /system/lib/egl/libEGL_mali.so
10-23 23:14:11.827: D/libEGL(26370): loaded /system/lib/egl/libGLESv1_CM_mali.so
10-23 23:14:11.827: D/libEGL(26370): loaded /system/lib/egl/libGLESv2_mali.so
10-23 23:14:11.887: D/OpenGLRenderer(26370): Enabling debug mode 0
10-23 23:14:16.762: D/AndroidRuntime(26370): Shutting down VM
10-23 23:14:16.762: W/dalvikvm(26370): threadid=1: thread exiting with uncaught exception (group=0x40aaa210)
10-23 23:14:16.802: E/AndroidRuntime(26370): FATAL EXCEPTION: main
10-23 23:14:16.802: E/AndroidRuntime(26370): java.lang.NullPointerException
10-23 23:14:16.802: E/AndroidRuntime(26370): at com.example.bmi.MainActivity.restore_(MainActivity.java:44)
10-23 23:14:16.802: E/AndroidRuntime(26370): at com.example.bmi.MainActivity.access$1(MainActivity.java:43)
10-23 23:14:16.802: E/AndroidRuntime(26370): at com.example.bmi.MainActivity$2.onClick(MainActivity.java:99)
10-23 23:14:16.802: E/AndroidRuntime(26370): at android.view.View.performClick(View.java:3574)
10-23 23:14:16.802: E/AndroidRuntime(26370): at android.view.View$PerformClick.run(View.java:14293)
10-23 23:14:16.802: E/AndroidRuntime(26370): at android.os.Handler.handleCallback(Handler.java:605)
10-23 23:14:16.802: E/AndroidRuntime(26370): at android.os.Handler.dispatchMessage(Handler.java:92)
10-23 23:14:16.802: E/AndroidRuntime(26370): at android.os.Looper.loop(Looper.java:137)
10-23 23:14:16.802: E/AndroidRuntime(26370): at android.app.ActivityThread.main(ActivityThread.java:4448)
10-23 23:14:16.802: E/AndroidRuntime(26370): at java.lang.reflect.Method.invokeNative(Native Method)
10-23 23:14:16.802: E/AndroidRuntime(26370): at java.lang.reflect.Method.invoke(Method.java:511)
10-23 23:14:16.802: E/AndroidRuntime(26370): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
10-23 23:14:16.802: E/AndroidRuntime(26370): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
10-23 23:14:16.802: E/AndroidRuntime(26370): at dalvik.system.NativeStart.main(Native Method)
This is the method to call the restore_()
private OnClickListener reback_1 = new OnClickListener() {
public void onClick(View v) {
restore_();
}
};
After I replaced the select_f and select_i into 0, it appeared the problem
10-24 00:01:30.957: D/TextLayoutCache(28836): Using debug level: 0 - Debug Enabled: 0
10-24 00:01:31.017: D/libEGL(28836): loaded /system/lib/egl/libGLES_android.so
10-24 00:01:31.037: D/libEGL(28836): loaded /system/lib/egl/libEGL_mali.so
10-24 00:01:31.057: D/libEGL(28836): loaded /system/lib/egl/libGLESv1_CM_mali.so
10-24 00:01:31.057: D/libEGL(28836): loaded /system/lib/egl/libGLESv2_mali.so
10-24 00:01:31.087: D/OpenGLRenderer(28836): Enabling debug mode 0
10-24 00:01:36.262: D/AndroidRuntime(28836): Shutting down VM
10-24 00:01:36.262: W/dalvikvm(28836): threadid=1: thread exiting with uncaught exception (group=0x40aaa210)
10-24 00:01:36.282: E/AndroidRuntime(28836): FATAL EXCEPTION: main
10-24 00:01:36.282: E/AndroidRuntime(28836): java.lang.NullPointerException
10-24 00:01:36.282: E/AndroidRuntime(28836): at com.example.bmi.MainActivity.restore_(MainActivity.java:44)
10-24 00:01:36.282: E/AndroidRuntime(28836): at com.example.bmi.MainActivity.access$1(MainActivity.java:43)
10-24 00:01:36.282: E/AndroidRuntime(28836): at com.example.bmi.MainActivity$2.onClick(MainActivity.java:99)
10-24 00:01:36.282: E/AndroidRuntime(28836): at android.view.View.performClick(View.java:3574)
10-24 00:01:36.282: E/AndroidRuntime(28836): at android.view.View$PerformClick.run(View.java:14293)
10-24 00:01:36.282: E/AndroidRuntime(28836): at android.os.Handler.handleCallback(Handler.java:605)
10-24 00:01:36.282: E/AndroidRuntime(28836): at android.os.Handler.dispatchMessage(Handler.java:92)
10-24 00:01:36.282: E/AndroidRuntime(28836): at android.os.Looper.loop(Looper.java:137)
10-24 00:01:36.282: E/AndroidRuntime(28836): at android.app.ActivityThread.main(ActivityThread.java:4448)
10-24 00:01:36.282: E/AndroidRuntime(28836): at java.lang.reflect.Method.invokeNative(Native Method)
10-24 00:01:36.282: E/AndroidRuntime(28836): at java.lang.reflect.Method.invoke(Method.java:511)
10-24 00:01:36.282: E/AndroidRuntime(28836): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
10-24 00:01:36.282: E/AndroidRuntime(28836): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
10-24 00:01:36.282: E/AndroidRuntime(28836): at dalvik.system.NativeStart.main(Native Method)
10-24 00:01:37.803: I/Process(28836): Sending signal. PID: 28836 SIG: 9
You are using the SharedPrefs wrong.
feet.setSelection(settings.getInt("DATA_FEET", select_f));
when you try to fetch the integer-value from sharedPref, you get returned null! because i think that you misunderstand how it is done:
settings.getInt("myKey", defaultValue);
returns you the value for the key "myKey". if "myKey" has no value set, then it returns you the "defaultValue". In your case it returns the current value of "select_f". And as it looks, the value of select_f is null, when you run your application for the first time.
So you have to decide whether to initialize "select_f" before you retrieve the sharedPrefs or you enter another defaultValue here.

App using camera flash as a torch using Eclipse not working

I have been working on an app to use a phone's/tablet's camera flash as a flashlight. Everything seemed to be working fine but when I tested it on my Droid Bionic running Android 4.1.2, the app failed to turn on the flash even though it said it did. Here is the java code I used:
package com.example.flash;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private boolean isFlashOn = false;
private Camera camera;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.buttonFlashlight);
Context context = this;
PackageManager pm = context.getPackageManager();
if(!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Log.e("err", "Device has no camera!");
Toast.makeText(getApplicationContext(),
"Your device doesn't have camera!",Toast.LENGTH_SHORT).show();
return;
}
camera = Camera.open();
final Parameters p = camera.getParameters();
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (isFlashOn) {
Log.i("info", "torch is turned off!");
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
isFlashOn = false;
button.setText("Tap to turn flashlight on.");
}
else {
Log.i("info", "torch is turned on!");
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
isFlashOn = true;
button.setText("Tap to turn flashlight off.");
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onStop() {
super.onStop();
if (camera != null) {
camera.release();
}
}}
Is this code correct or did I miss something?
Logcat:
07-03 18:48:29.064: E/Trace(773): error opening trace file: No such file or directory (2)
07-03 18:48:30.535: D/Camera(773): app passed NULL surface
07-03 18:48:31.023: D/libEGL(773): loaded /system/lib/egl/libEGL_emulation.so
07-03 18:48:31.073: D/(773): HostConnection::get() New Host Connection established 0x2a13c3c0, tid 773
07-03 18:48:31.123: D/libEGL(773): loaded /system/lib/egl/libGLESv1_CM_emulation.so
07-03 18:48:31.173: D/libEGL(773): loaded /system/lib/egl/libGLESv2_emulation.so
07-03 18:48:31.406: W/EGL_emulation(773): eglSurfaceAttrib not implemented
07-03 18:48:31.433: D/OpenGLRenderer(773): Enabling debug mode 0
07-03 18:48:31.723: I/Choreographer(773): Skipped 58 frames! The application may be doing too much work on its main thread.
07-03 18:49:05.923: D/dalvikvm(773): GC_CONCURRENT freed 202K, 12% free 2623K/2956K, paused 74ms+25ms, total 234ms
07-03 18:49:06.216: W/EGL_emulation(773): eglSurfaceAttrib not implemented
07-03 18:49:09.584: D/Camera(773): app passed NULL surface
07-03 18:49:09.853: W/EGL_emulation(773): eglSurfaceAttrib not implemented
07-03 18:49:11.813: I/info(773): torch is turned on!
07-03 18:49:13.467: I/info(773): torch is turned off!
07-03 18:49:16.263: W/EGL_emulation(773): eglSurfaceAttrib not implemented
07-03 18:49:16.713: D/AndroidRuntime(773): Shutting down VM
07-03 18:49:16.713: W/dalvikvm(773): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
07-03 18:49:16.936: E/AndroidRuntime(773): FATAL EXCEPTION: main
07-03 18:49:16.936: E/AndroidRuntime(773): java.lang.RuntimeException: Method called after release()
07-03 18:49:16.936: E/AndroidRuntime(773): at android.hardware.Camera._stopPreview(Native Method)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.hardware.Camera.stopPreview(Camera.java:543)
07-03 18:49:16.936: E/AndroidRuntime(773): at com.example.flash.MainActivity.surfaceDestroyed(MainActivity.java:140)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.SurfaceView.updateWindow(SurfaceView.java:553)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.SurfaceView.onWindowVisibilityChanged(SurfaceView.java:231)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.View.dispatchWindowVisibilityChanged(View.java:7544)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1039)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1039)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1039)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.ViewGroup.dispatchWindowVisibilityChanged(ViewGroup.java:1039)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1211)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.Choreographer.doCallbacks(Choreographer.java:562)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.Choreographer.doFrame(Choreographer.java:532)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.os.Handler.handleCallback(Handler.java:725)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.os.Handler.dispatchMessage(Handler.java:92)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.os.Looper.loop(Looper.java:137)
07-03 18:49:16.936: E/AndroidRuntime(773): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-03 18:49:16.936: E/AndroidRuntime(773): at java.lang.reflect.Method.invokeNative(Native Method)
07-03 18:49:16.936: E/AndroidRuntime(773): at java.lang.reflect.Method.invoke(Method.java:511)
07-03 18:49:16.936: E/AndroidRuntime(773): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-03 18:49:16.936: E/AndroidRuntime(773): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-03 18:49:16.936: E/AndroidRuntime(773): at dalvik.system.NativeStart.main(Native Method)
07-03 18:49:24.854: E/Trace(811): error opening trace file: No such file or directory (2)
07-03 18:49:25.413: D/libEGL(811): loaded /system/lib/egl/libEGL_emulation.so
07-03 18:49:25.567: D/(811): HostConnection::get() New Host Connection established 0x2a15f570, tid 811
07-03 18:49:25.643: D/libEGL(811): loaded /system/lib/egl/libGLESv1_CM_emulation.so
07-03 18:49:25.663: D/libEGL(811): loaded /system/lib/egl/libGLESv2_emulation.so
07-03 18:49:25.934: W/EGL_emulation(811): eglSurfaceAttrib not implemented
07-03 18:49:25.963: D/OpenGLRenderer(811): Enabling debug mode 0
07-03 18:53:12.298: D/Camera(811): app passed NULL surface
07-03 18:53:12.723: D/dalvikvm(811): GC_CONCURRENT freed 172K, 11% free 2600K/2904K, paused 9ms+165ms, total 421ms
07-03 18:53:12.934: E/EGL_emulation(811): rcCreateWindowSurface returned 0
07-03 18:53:12.934: E/EGL_emulation(811): tid 811: eglCreateWindowSurface(631): error 0x3003 (EGL_BAD_ALLOC)
07-03 18:53:12.943: D/AndroidRuntime(811): Shutting down VM
07-03 18:53:12.943: W/dalvikvm(811): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
07-03 18:53:13.033: E/AndroidRuntime(811): FATAL EXCEPTION: main
07-03 18:53:13.033: E/AndroidRuntime(811): java.lang.RuntimeException: createWindowSurface failed EGL_BAD_ALLOC
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.HardwareRenderer$GlRenderer.createSurface(HardwareRenderer.java:1064)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.HardwareRenderer$GlRenderer.createEglSurface(HardwareRenderer.java:961)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.HardwareRenderer$GlRenderer.initialize(HardwareRenderer.java:787)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1502)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:989)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4351)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.Choreographer.doCallbacks(Choreographer.java:562)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.Choreographer.doFrame(Choreographer.java:532)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.os.Handler.handleCallback(Handler.java:725)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.os.Handler.dispatchMessage(Handler.java:92)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.os.Looper.loop(Looper.java:137)
07-03 18:53:13.033: E/AndroidRuntime(811): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-03 18:53:13.033: E/AndroidRuntime(811): at java.lang.reflect.Method.invokeNative(Native Method)
07-03 18:53:13.033: E/AndroidRuntime(811): at java.lang.reflect.Method.invoke(Method.java:511)
07-03 18:53:13.033: E/AndroidRuntime(811): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-03 18:53:13.033: E/AndroidRuntime(811): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-03 18:53:13.033: E/AndroidRuntime(811): at dalvik.system.NativeStart.main(Native Method)
UPDATE
I think the key is you are running Android 4.1.2. Since Android 4.0, if you want to use the Camera Device, even if you only want to use the flash, you are forced to use a SurfaceView.
In the previous answer (below), I gave you a link to a Torch app which uses SurfaceView. Try it or adapt it to your code.
PREVIOUS ANSWER:
As stated in many other cases (like this one), you may be facing a Device-Specific issue that is quite common in the Android world.
Although getSupportedFlashModes() may return FLASH_MODE_TORCH on nearly every device, many of them don't actually support it.
Anyway, you could try these:
Use camera.startPreview(); after camera = Camera.open();
Try setting FLASH_MODE_OFF initially (before camera.startPreview();).
Check if this Torch app works in your device. In case it does, you have the source code to compare it to yours.
Download a Torch app from the Play Store to test if it's a device issue or not.
Post the issue in a Droid Bionic support forum.
UPDATE: I would say the final keyword is a problem in your code. Try changing it to:
//camera = Camera.open();
//final Parameters p = camera.getParameters();
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (isFlashOn) {
Log.i("info", "torch is turned off!");
cam.stopPreview();
cam.release();
isFlashOn = false;
button.setText("Tap to turn flashlight on.");
}
else {
Log.i("info", "torch is turned on!");
camera = Camera.open();
Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.startPreview();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
isFlashOn = true;
button.setText("Tap to turn flashlight off.");
}
}
});
user the permission "android.permission.FLASHLIGHT" in the manifest
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.CAMERA" />

Calling static method in one Activity from another Activity

I have these methods in X.class:
public void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
//mOutEditText.setText(mOutStringBuffer);
}
}
public static void sendMessage1(String message1){
call1.sendMessage(message1);
}
And I have the following toggleSwitch that Im clicking from another acitvity namely Y.class:
tb3.setOnClickListener(new OnClickListener() {
public void onClick(View v){
if (tb3.isChecked()){
String message = "u";
X.sendMessage1(message);
//clearer();
} else if (!tb3.isChecked()){
String message = "y";
//clearer();
}
}
});
Though I'm not getting any errors while coding but when I load the app on Android and then click on this toggleswitch my app dies?
Log:
E/AndroidRuntime( 4866): java.lang.NullPointerException
E/AndroidRuntime( 4866): at com.winacro.andRHOME.andRHOME.sendMessage1(andRHOME.java:282)
E/AndroidRuntime( 4866): at com.winacro.andRHOME.EECA2$1.onClick(EECA2.java:57)
E/AndroidRuntime( 4866): at android.view.View.performClick(View.java:3534)
E/AndroidRuntime( 4866): at android.widget.CompoundButton.performClick(CompoundButton.java:104)
E/AndroidRuntime( 4866): at android.view.View$PerformClick.run(View.java:14263)
E/AndroidRuntime( 4866): at android.os.Handler.handleCallback(Handler.java:605)
E/AndroidRuntime( 4866): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime( 4866): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime( 4866): at android.app.ActivityThread.main(ActivityThread.java:4441)
E/AndroidRuntime( 4866): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 4866): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime( 4866): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
E/AndroidRuntime( 4866): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
E/AndroidRuntime( 4866): at dalvik.system.NativeStart.main(Native Method)
W/ActivityManager( 273): Force finishing activity com.winacro.andRHOME/.EECA2

Categories