ImageLoader NullPointerException for an off-screen, SlidingMenu item? - java

I'm parsing a JSON response from a weather feed and the data I receive includes a url to an icon that corresponds with the conditions, then I display that icon in an ImageView. I was able to make this work in a sandbox app before moving the package of code into my project.
In the main project I use the latest versions of ActionBarSherlock and SlidingMenu for navigation, and both apps make use of Android-Async-Http-Client but now it has a fatal NullPointerException when trying to display the icon from that url in the ImageView. I don't think this is caused by any of the libraries.
I've seen that sliding menus mostly consist of some type of ListView handled with an Adapter, which I'm doing in a portion of my sliding menu. But the only clue I have is that it crashes because now it's an off-screen UI element that I'm trying to work with. Does it matter that I have something in my sliding menu that isn't handled by an Adapter? I can't imagine much else is different but maybe you guys some clue of what I'm missing. Hopefully it isn't something basic that I'm just forgetting... or maybe it is :)
Alright, thanks for any ideas.
public class MainActivity extends SlidingActivity implements
ActionBar.OnNavigationListener {
final String TAG = "MainActivity";
private TextView mSelected;
private String[] mLocations;
ImageLoader imageLoader;
ImageView weatherIcon;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageLoader = new ImageLoader(this);
wireViews();
getWeatherFeed();
Context context = getSupportActionBar().getThemedContext();
ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(
context, R.array.activities, R.layout.sherlock_spinner_item);
list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
getSupportActionBar().setListNavigationCallbacks(list, this);
getSupportActionBar().setDisplayShowTitleEnabled(false);
// set the Behind View
setBehindContentView(R.layout.menu_frame);
// SlidingMenu
SlidingMenu sm = getSlidingMenu();
sm.setShadowWidthRes(R.dimen.shadow_width);
sm.setShadowDrawable(R.drawable.shadow);
sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
sm.setFadeDegree(0.35f);
sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setSlidingActionBarEnabled(false);
ListView menuList = (ListView) findViewById(R.id.menuList);
SlidingMenuItem[] data = new SlidingMenuItem[] {
new SlidingMenuItem("Item1 Label", "Item1 Sub-label",getResources().getDrawable(R.drawable.item1)),
new SlidingMenuItem("Item2 Label", "Item2 Sub-Label",getResources().getDrawable(R.drawable.item2)) };
MenuAdapter adapter = new MenuAdapter(this, R.layout.sliding_menu_item,
data);
menuList.setAdapter(adapter);
}
private void updateWeatherUi(String degreeText, String descriptionText,
String iconUrl) {
Log.i(TAG, "Updating UI elements...");
if (imageLoader != null) {
Log.i(TAG, "IMAGE_LOADER NOT NULL!!!");
}
imageLoader.DisplayImage(iconUrl, weatherIcon); // FIXME: FATAL CRASH HERE !!!
}
/** Build a Weather object from the JSON response.
* #throws JSONException */
private void buildWeatherObject(String rawResponse) throws JSONException {
Log.i(TAG, "Building Weather ojbect...");
JSONObject baseObject = new JSONObject(rawResponse);
JSONObject data = new JSONObject(baseObject.getString(Key.DATA));
JSONArray conditionArray = new JSONArray(
data.getString(Key.CURRENT_CONDITION));
for (int i = 0; i < conditionArray.length(); i++) {
JSONObject conditionElement = new JSONObject(
conditionArray.getString(i));
weather = new Weather();
weather.tempMaxF = conditionElement.getString(Key.TEMP_F);
JSONArray weatherDescriptionArray = new JSONArray(
conditionElement.getString(Key.W_WEATHER_DESC));
for (int j = 0; j < weatherDescriptionArray.length(); j++) {
JSONObject weatherDescriptionElement = new JSONObject(
weatherDescriptionArray.getString(j));
weather.weatherDesc = weatherDescriptionElement
.getString(Key.VALUE);
}
JSONArray weatherIconArray = new JSONArray(
conditionElement.getString(Key.WEATHER_ICON_URL));
for (int j = 0; j < weatherIconArray.length(); j++) {
JSONObject weatherIconElement = new JSONObject(
weatherIconArray.getString(j));
weather.weatherIconUrl = weatherIconElement
.getString(Key.VALUE);
Log.i(TAG, weather.weatherIconUrl);
}
conditionElement = null;
updateWeatherUi(weather.tempMaxF, weather.weatherDesc,
weather.weatherIconUrl);
}
}
/** Asynchronously request and receive weather feed data. */
private void getWeatherFeed() {
Log.i(TAG, "Getting asynchronous JSON feed...");
AsyncHttpClient client = new AsyncHttpClient();
client.get(WEATHER_FEED_URL, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
try {
buildWeatherObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable arg0, String arg1) {
super.onFailure(arg0, arg1);
showToast("Sorry, the weather forecast wasn't available just then.");
}
});
}
private void wireViews() {
Log.i(TAG, "Wiring UI elements...");
mSelected = (TextView) findViewById(R.id.text);
mLocations = getResources().getStringArray(R.array.activities);
weatherIcon = (ImageView) findViewById(R.id.weatherIconView);
}
12-21 01:01:11.130: I/MainActivity(28502): Building Weather ojbect...
12-21 01:01:11.170: I/MainActivity(28502): http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png
12-21 01:01:11.170: I/MainActivity(28502): Updating UI elements...
12-21 01:01:11.170: I/MainActivity(28502): IMAGE_LOADER NOT NULL!!!
12-21 01:01:11.170: D/AndroidRuntime(28502): Shutting down VM
12-21 01:01:11.170: W/dalvikvm(28502): threadid=1: thread exiting with uncaught exception (group=0x4001d5a0)
12-21 01:01:11.180: E/AndroidRuntime(28502): FATAL EXCEPTION: main
12-21 01:01:11.180: E/AndroidRuntime(28502): java.lang.NullPointerException
12-21 01:01:11.180: E/AndroidRuntime(28502): at com.eric.app.networkxml.ImageLoader.DisplayImage(ImageLoader.java:42)
12-21 01:01:11.180: E/AndroidRuntime(28502): at com.eric.app.MainActivity.updateWeatherUi(MainActivity.java:129)
12-21 01:01:11.180: E/AndroidRuntime(28502): at com.eric.app.MainActivity.buildWeatherObject(MainActivity.java:172)
12-21 01:01:11.180: E/AndroidRuntime(28502): at com.eric.app.MainActivity.access$0(MainActivity.java:137)
12-21 01:01:11.180: E/AndroidRuntime(28502): at com.eric.app.MainActivity$1.onSuccess(MainActivity.java:195)
12-21 01:01:11.180: E/AndroidRuntime(28502): at com.loopj.android.http.AsyncHttpResponseHandler.handleSuccessMessage(AsyncHttpResponseHandler.java:160)
12-21 01:01:11.180: E/AndroidRuntime(28502): at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:173)
12-21 01:01:11.180: E/AndroidRuntime(28502): at com.loopj.android.http.AsyncHttpResponseHandler$1.handleMessage(AsyncHttpResponseHandler.java:85)
12-21 01:01:11.180: E/AndroidRuntime(28502): at android.os.Handler.dispatchMessage(Handler.java:99)
12-21 01:01:11.180: E/AndroidRuntime(28502): at android.os.Looper.loop(Looper.java:150)
12-21 01:01:11.180: E/AndroidRuntime(28502): at android.app.ActivityThread.main(ActivityThread.java:4263)
12-21 01:01:11.180: E/AndroidRuntime(28502): at java.lang.reflect.Method.invokeNative(Native Method)
12-21 01:01:11.180: E/AndroidRuntime(28502): at java.lang.reflect.Method.invoke(Method.java:507)
12-21 01:01:11.180: E/AndroidRuntime(28502): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-21 01:01:11.180: E/AndroidRuntime(28502): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-21 01:01:11.180: E/AndroidRuntime(28502): at dalvik.system.NativeStart.main(Native Method)
Yikes! I tried to post a "snippet" but maybe I should've posted the complete file...

Putting the updateWeatherUi() logic at inside the end of buildWeatherObject() fixed this for me.
The problem is that I'm still not sure what was occurring here previously. The Logs were showing the proper data right up to the point of imageLoader.DisplayImage(String, ImageView) in my original code but I kept crashing there with NullPointerException.

Related

NullPointerException in savedInstanceState Bundle

I am getting a NullPointerException when my code tries to access the value in a key/value pair created by onSaveInstanceState method of Activity class.
I set break points and I know for fact my Bundle is not null and it contains references to my key/values. I dont understand why I am getting this runtime error. Here are my codes for onSaveInstanceState
#Override
protected void onSaveInstanceState(Bundle outState) {
int mPoints = winCount;
int hPoints = loseCount;
String reTextView = resultsTextView.getText().toString();
String pTextView = pointsTextView.getText().toString();
String roTextView = rollTextView.getText().toString();
outState.putInt("MY_POINTS", mPoints);
outState.putInt("HOUSE_POINTS", hPoints);
outState.putString("RESULTS", reTextView);
outState.putString("POINTS", pTextView);
outState.putString("ROLL", roTextView);
super.onSaveInstanceState(outState);
}
and here is my code to restore the state on the onCreate method
// check if app just started or is being restored from memory
if ( savedInstanceState == null ) // the app just started running
{
winCount = 0;
loseCount = 0;
}
else
{
winCount = savedInstanceState.getInt("MY_POINTS");
loseCount = savedInstanceState.getInt("HOUSE_POINTS");
resultsTextView.setText(String.valueOf(savedInstanceState.getString("RESULTS")));
pointsTextView.setText(String.valueOf(savedInstanceState.getString("POINTS")));
rollTextView.setText(String.valueOf(savedInstanceState.getString("ROLL")));
}
I get the runtime error on line that starts with resultsTextView.setText... and here is contents of the savedInstanceState Bundle retrieved from break points in debug mode
Bundle[{RESULTS=Roll Again, MY_POINTS=2, POINTS=Your Point is 8,
HOUSE_POINTS=2,
android:viewHierarchyState=Bundle[{android:Panels=android.util.SparseArray#421c5560,
android:views=android.util.SparseArray#421c5358,
android:ActionBar=android.util.SparseArray#421c57f8}], ROLL=You Rolled
Easy Four}]
as you can see all my strings have a value, the interesting thing is that I dont get the NullPointerException runtime error on int variables (winCount and loseCount) but I am getting it at string values. I appreciate any help.
Update: here is the whole error log from log cat, I have resultsTextView.setText... at line 68 (within the else block on onCreat())
W/dalvikvm(27797): threadid=1: thread exiting with uncaught exception (group=0x418b6700)
E/AndroidRuntime(27797): FATAL EXCEPTION: main
E/AndroidRuntime(27797): java.lang.RuntimeException: Unable to start activity ComponentInfo{…}: java.lang.NullPointerException
E/AndroidRuntime(27797): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
E/AndroidRuntime(27797): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
E/AndroidRuntime(27797): at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3740)
E/AndroidRuntime(27797): at android.app.ActivityThread.access$700(ActivityThread.java:141)
E/AndroidRuntime(27797): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1262)
E/AndroidRuntime(27797): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime(27797): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(27797): at android.app.ActivityThread.main(ActivityThread.java:5103)
E/AndroidRuntime(27797): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(27797): at java.lang.reflect.Method.invoke(Method.java:525)
E/AndroidRuntime(27797): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
E/AndroidRuntime(27797): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime(27797): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime(27797): Caused by: java.lang.NullPointerException
E/AndroidRuntime(27797): at app.package.onCreate(AppName.java:68)
E/AndroidRuntime(27797): at android.app.Activity.performCreate(Activity.java:5133)
E/AndroidRuntime(27797): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
E/AndroidRuntime(27797): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
E/AndroidRuntime(27797): ... 12 more
here is my whole onCreate method, since many commentators requested to see the whole method. Hope it helps!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
// check if app just started or is being restored from memory
if ( savedInstanceState == null ) // the app just started running
{
winCount = 0;
loseCount = 0;
}
else
{
winCount = savedInstanceState.getInt("MY_POINTS");
loseCount = savedInstanceState.getInt("HOUSE_POINTS");
resultsTextView.setText(savedInstanceState.getString("RESULTS"));
pointsTextView.setText(savedInstanceState.getString("POINTS"));
rollTextView.setText(savedInstanceState.getString("ROLL"));
}
die1 = (ImageView) findViewById(R.id.imageView1);
die2 = (ImageView) findViewById(R.id.imageView2);
dealButton = (Button) findViewById(R.id.dealButton);
resetButton = (Button) findViewById(R.id.resetButton);
resultsTextView = (TextView) findViewById(R.id.resultsTextView);
myPointsTextView = (TextView) findViewById(R.id.myPointstTextView);
housePointsTextView = (TextView) findViewById(R.id.housePointsTextView);
pointsTextView = (TextView) findViewById(R.id.pointsTextView1);
rollTextView = (TextView) findViewById(R.id.rollTextView);
dealButton.setOnClickListener(dealButtonListener);
resetButton.setOnClickListener(resetButtonLinstener);
//on shake event
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mShakeDetector = new ShakeDetector(new OnShakeListener() {
#Override
public void onShake() {
game(rollDice());
}
});
resultsTextView.setTextColor(Color.BLACK);
myPointsTextView.setText(String.format("%s", winCount));
housePointsTextView.setText(String.format("%s", loseCount));
}
You should initialize your TextViews before calling setText method. So onCreate should be like this:
setContentView(R.layout.activity);
die1 = (ImageView) findViewById(R.id.imageView1);
die2 = (ImageView) findViewById(R.id.imageView2);
dealButton = (Button) findViewById(R.id.dealButton);
resetButton = (Button) findViewById(R.id.resetButton);
resultsTextView = (TextView) findViewById(R.id.resultsTextView);
myPointsTextView = (TextView) findViewById(R.id.myPointstTextView);
housePointsTextView = (TextView) findViewById(R.id.housePointsTextView);
pointsTextView = (TextView) findViewById(R.id.pointsTextView1);
rollTextView = (TextView) findViewById(R.id.rollTextView);
// check if app just started or is being restored from memory
if ( savedInstanceState == null ) // the app just started running
{
winCount = 0;
loseCount = 0;
}
else
{
winCount = savedInstanceState.getInt("MY_POINTS");
loseCount = savedInstanceState.getInt("HOUSE_POINTS");
resultsTextView.setText(savedInstanceState.getString("RESULTS"));
pointsTextView.setText(savedInstanceState.getString("POINTS"));
rollTextView.setText(savedInstanceState.getString("ROLL"));
}
...

Using the runOnUiThread to update Listview

I have written a thread that uses runOnUiThread to update the listview approximately every 500ms. This thread is written outside OnCreate(), but is called from OnCreate. Everything compiles fine, but I seem to be getting an error that tells me that my adapter is null, even though I use that same adapter to "initialize" the listview in OnCreate. I have posted both my code and my log. The main error that I run into, java.lang.NullPointerException, refers to line 454 of the MainActivity, which in this case is adapter.notifyDataSetChanged();. Any help would be greatly appreciated.
MainActivity
public class MainActivity extends Activity
{
// Sensor Constants
public static String temperature;
public static String humidity;
public static String lpg;
public static String alcohol;
public static int temperature_int;
public static int humidity_int;
public static int lpg_int;
public static int alcohol_int;
// Layout
ListView listView;
ItemAdapter adapter;
// USB
UsbManager USB_Manager;
UsbDevice Sense;
PendingIntent permission;
IntentFilter filter;
//BroadcastReceiver receiver;
//USBBuffer_s_received_data = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialize Interface
Model.LoadModel();
listView = (ListView) findViewById(R.id.listView);
String[] ids = new String[Model.Items.size()];
for (int i= 0; i < ids.length; i++)
{ids[i] = Integer.toString(i+1);}
ItemAdapter adapter = new ItemAdapter(this,R.layout.row, ids);
listView.setAdapter(adapter);
//USB
if ((UsbManager) getSystemService(Context.USB_SERVICE) != null)
{
USB_Manager = (UsbManager) getSystemService(Context.USB_SERVICE);
if (USB_Manager.getDeviceList().values().iterator().next() != null)
{
Sense = USB_Manager.getDeviceList().values().iterator().next();
if ((UsbDevice) getIntent().getParcelableExtra(UsbManager.EXTRA_DEVICE) != null)
{
Sense = (UsbDevice) getIntent().getParcelableExtra(UsbManager.EXTRA_DEVICE);
}
}
}
// Update Layout
temperature_int = 30; humidity_int = 6; lpg_int = 5000; alcohol_int = 500;
temperature = String.valueOf(temperature_int);
humidity = String.valueOf(humidity_int);
lpg = String.valueOf(lpg_int);
alcohol = String.valueOf(alcohol_int);
Model.LoadModel();
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
GUI_Update();
}
#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;
}
private void GUI_Update()
{
new Thread()
{
public void run()
{
while (true)
{
try
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
Model.LoadModel();
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
});
Thread.sleep(500);
}
catch (InterruptedException e)
{
}
}
}
}.start();
}
}
Log
12-21 14:39:02.109: D/AndroidRuntime(32704): Shutting down VM
12-21 14:39:02.109: W/dalvikvm(32704): threadid=1: thread exiting with uncaught exception (group=0x4198ac68)
12-21 14:39:02.109: E/AndroidRuntime(32704): FATAL EXCEPTION: main
12-21 14:39:02.109: E/AndroidRuntime(32704): Process: com.byrdonatwigge.sense, PID: 32704
12-21 14:39:02.109: E/AndroidRuntime(32704): java.lang.NullPointerException
12-21 14:39:02.109: E/AndroidRuntime(32704): at com.byrdonatwigge.sense.MainActivity$2$1.run(MainActivity.java:454)
12-21 14:39:02.109: E/AndroidRuntime(32704): at android.os.Handler.handleCallback(Handler.java:733)
12-21 14:39:02.109: E/AndroidRuntime(32704): at android.os.Handler.dispatchMessage(Handler.java:95)
12-21 14:39:02.109: E/AndroidRuntime(32704): at android.os.Looper.loop(Looper.java:136)
12-21 14:39:02.109: E/AndroidRuntime(32704): at android.app.ActivityThread.main(ActivityThread.java:5081)
12-21 14:39:02.109: E/AndroidRuntime(32704): at java.lang.reflect.Method.invokeNative(Native Method)
12-21 14:39:02.109: E/AndroidRuntime(32704): at java.lang.reflect.Method.invoke(Method.java:515)
12-21 14:39:02.109: E/AndroidRuntime(32704): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:781)
12-21 14:39:02.109: E/AndroidRuntime(32704): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-21 14:39:02.109: E/AndroidRuntime(32704): at dalvik.system.NativeStart.main(Native Method)
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initialize Interface
Model.LoadModel();
listView = (ListView) findViewById(R.id.listView);
String[] ids = new String[Model.Items.size()];
for (int i= 0; i < ids.length; i++)
{ids[i] = Integer.toString(i+1);}
// change following line:
this.adapter = new ItemAdapter(this,R.layout.row, ids);
You are creating a local variable adapter in your onCreate() and assigning a new ItemAdapter to it.
ItemAdapter adapter = new ItemAdapter(this,R.layout.row, ids);
This is called variable shadowing; that variable has absolutely nothing to do with the instance field adapter that you're trying to use in GUI_Update() .. which is why it's null there, and throws the NPE.
Your IDE should actually be pointing that out to you.

Android takepicture failed at Android version 4.1.1 but succeed in version 4.0.0

I got the LogCat :
java.lang.RuntimeException: takePicture failed
at android.hardware.Camera.native_takePicture(Native Method)
at android.hardware.Camera.takePicture(Camera.java:1061)
at android.hardware.Camera.takePicture(Camera.java:1006)
at com.cidtech.portraitcatch.service.MyService.takePic(MyService.java:168)
at com.cidtech.portraitcatch.service.MyService$1.onClick(MyService.java:78)
at android.view.View.performClick(View.java:4088)
at android.view.View$PerformClick.run(View.java:16984)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
the curial code is below:
public void takePic(){
home_takePic.setEnabled(false);
camera = Camera.open();
if(bitmapList == null){
bitmapList = new ArrayList<Bitmap>();
}
for(int i=0; i<5; i++){
camera.takePicture(null, null, new MyPictureCallback());
SystemClock.sleep(1000);
}
saveBitmapToSdcard();
releaseResource();
home_takePic.setEnabled(true);
}
I also do this:
public void takePic(){
home_takePic.setEnabled(false);
camera = Camera.open();
***camera.startPreview();***
if(bitmapList == null){
bitmapList = new ArrayList<Bitmap>();
}
for(int i=0; i<5; i++){
camera.takePicture(null, null, new MyPictureCallback());
SystemClock.sleep(1000);
}
// saveBitmapToSdcard();
releaseResource();
home_takePic.setEnabled(true);
}
but still get the same Exception
the method camera.takePicture have been performed in version 4.0.4 but faild in version 4.1.1, who can tell me how to solve it ,please help me ,thanks
You need to be making a call to startPreview() before you attempt the call to takePicture(). Do this after you call Camera.open().
As per Android documentation:
Important: Call startPreview() to start updating the preview surface.
Preview must be started before you can take a picture.
startPreview documentation

Android displaying image from Database

Hi I learned how to grab data from a SQL and display onto TextView. But I'm having little trouble displaying images.
The images are stored in the SQL database as URL but I can't display as an image onto the view.
I've done some research and found on "How to display image with given URL", but I'm just having a little difficulty understanding the concept of grabbing the URL and display .. Please kindly help me. Thank you!
This is the errorLog i'm getting.
Update
Line 159 : photoMe.setImageDrawable(drawable);
11-15 14:53:21.450: W/LoadImageFromWebOperations(28444): java.net.MalformedURLException: Protocol not found: photo
11-15 14:53:21.480: D/AndroidRuntime(28444): Shutting down VM
11-15 14:53:21.480: W/dalvikvm(28444): threadid=1: thread exiting with uncaught exception (group=0x40c55a68)
11-15 14:53:21.500: E/AndroidRuntime(28444): FATAL EXCEPTION: main
11-15 14:53:21.500: E/AndroidRuntime(28444): java.lang.NullPointerException
11-15 14:53:21.500: E/AndroidRuntime(28444): at com.app.android.DirectoryDetailMeActivity$GetDirectoryDetails$1.run(DirectoryDetailMeActivity.java:159)
11-15 14:53:21.500: E/AndroidRuntime(28444): at android.os.Handler.handleCallback(Handler.java:605)
11-15 14:53:21.500: E/AndroidRuntime(28444): at android.os.Handler.dispatchMessage(Handler.java:92)
11-15 14:53:21.500: E/AndroidRuntime(28444): at android.os.Looper.loop(Looper.java:137)
11-15 14:53:21.500: E/AndroidRuntime(28444): at android.app.ActivityThread.main(ActivityThread.java:4517)
11-15 14:53:21.500: E/AndroidRuntime(28444): at java.lang.reflect.Method.invokeNative(Native Method)
11-15 14:53:21.500: E/AndroidRuntime(28444): at java.lang.reflect.Method.invoke(Method.java:511)
11-15 14:53:21.500: E/AndroidRuntime(28444): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
11-15 14:53:21.500: E/AndroidRuntime(28444): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
11-15 14:53:21.500: E/AndroidRuntime(28444): at dalvik.system.NativeStart.main(Native Method)
public class DirectoryDetailMeActivity extends Activity {
ImageView photoMe;
TextView txtName;
String uid;
String photo = "";
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String url_veiw_directory = "directory_detail_me.php";
private static final String TAG_ID = "uid";
private static final String TAG_IMG = "photo";
private static final String TAG_NAME = "name";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.directory_detail_me);
uid = i.getStringExtra(TAG_ID);
new GetDirectoryDetails().execute();
}
class GetDirectoryDetails extends AsyncTask<String, String, String> {
protected String doInBackground(String... params) {
runOnUiThread(new Runnable() {
public void run() {
int success;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", uid));
JSONObject json = jsonParser.makeHttpRequest(url_veiw_directory, "GET", params);
Log.d("my profile", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
JSONArray directoryObj = json.getJSONArray(TAG_DIRECTORY);
JSONObject directory = directoryObj.getJSONObject(0);
txtName.setText(directory.getString(TAG_NAME));
Drawable drawable = LoadImageURL(TAG_IMG);
photoMe.setImageDrawable(drawable);
txtName = (TextView) findViewById(R.id.name);
photoMe = (ImageView) findViewById(R.id.photo);
}else{
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private Drawable LoadImageURL(String url)
{
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "photo");
return d;
}
catch (Exception e)
{
Log.w("LoadImageURL",e.toString());
return null;
}
}
});
return null;
}
}
}
You don't seem to understand an AsyncTask. The point is that it does not run on the UI thread, making it possible to do long term IO like HTTP connections. Wrapping the entire doInBackground in a runOnUIThread is completely counter to that. Its not your only problem, but its on the list.
The rest is too hard to read due to formatting, but look on line 159. Some variable you're using there is null.

Android App crashing in method when used on actual device but works fully in Eclipse

This is a Android application with sdk set as:
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="11"/>
The problem is that the app will run fine in the Eclipse Environment on a AVD. When I install directly to the phone or even set the phone as the device to use in Eclipse the app fails in the below area of code. To narrow down where the error was occurring I placed some toast's along the way and the "clicked" toast displays but the "Intent Created" does not. So that leaves me with only 2 lines, but I can not figure out for the life of me why it dies in that area. Code of the method with the toast's in it is as follows:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String bid = ((TextView) view.findViewById(R.id.bid)).getText()
.toString();
Toast.makeText(getApplicationContext(), "clicked", Toast.LENGTH_LONG).show();
Intent in = new Intent(getApplicationContext(),
BusinessDetails.class);
in.putExtra(TAG_BID, bid);
Toast.makeText(getApplicationContext(), "Intent Created", Toast.LENGTH_LONG).show();
startActivityForResult(in, 100);
}
});
BusinessDetails Class to the bundle method is as follows:
package com.example.businessLookUp;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
public class BusinessDetails extends Activity {
EditText txtDesc;
Button btnSave;
String bid;
String _bname;
String _phone;
String _address;
String _city;
String _state;
String _zip;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
private static final String url_business_detials = "http://192.168.1.2/get_business_details.php";
private static final String url_update_details = "http://192.168.1.2/update_business.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_BUSINESS = "business";
private static final String TAG_BID = "bid";
private static final String TAG_NAME = "name";
private static final String TAG_ADDRESS = "address";
private static final String TAG_CITY = "city";
private static final String TAG_STATE = "state";
private static final String TAG_ZIP = "zip";
private static final String TAG_PHONE = "phone";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_business);
// save button
btnSave = (Button) findViewById(R.id.btnSave);
Intent i = getIntent();
bid = i.getStringExtra(TAG_BID);
Toast.makeText(getApplicationContext(), "check 1", Toast.LENGTH_LONG).show();
// Getting complete product details in background thread
new GetBusinessDetails().execute();
The BusinessDetails was truncated here because the line below is never reached:
Toast.makeText(getApplicationContext(), "check 1", Toast.LENGTH_LONG).show();
which tells me that the code is never even reached... Any ideas where this is going wrong at???
LogCat Exception:
10-27 16:39:28.834: E/AndroidRuntime(25260): FATAL EXCEPTION: main
10-27 16:39:28.834: E/AndroidRuntime(25260): android.os.NetworkOnMainThreadException
10-27 16:39:28.834: E/AndroidRuntime(25260): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1119)
10-27 16:39:28.834: E/AndroidRuntime(25260): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
10-27 16:39:28.834: E/AndroidRuntime(25260): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
10-27 16:39:28.834: E/AndroidRuntime(25260): at libcore.io.IoBridge.connect(IoBridge.java:112)
10-27 16:39:28.834: E/AndroidRuntime(25260): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
10-27 16:39:28.834: E/AndroidRuntime(25260): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
10-27 16:39:28.834: E/AndroidRuntime(25260): at java.net.Socket.connect(Socket.java:842)
10-27 16:39:28.834: E/AndroidRuntime(25260): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
10-27 16:39:28.834: E/AndroidRuntime(25260): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
10-27 16:39:28.834: E/AndroidRuntime(25260): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
10-27 16:39:28.834: E/AndroidRuntime(25260): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
10-27 16:39:28.834: E/AndroidRuntime(25260): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
10-27 16:39:28.834: E/AndroidRuntime(25260): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
10-27 16:39:28.834: E/AndroidRuntime(25260): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
10-27 16:39:28.834: E/AndroidRuntime(25260): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
10-27 16:39:28.834: E/AndroidRuntime(25260): at com.example.businesslookup.JSONParser.makeHttpRequest(JSONParser.java:65)
10-27 16:39:28.834: E/AndroidRuntime(25260): at com.example.businesslookup.BusinessDetails$GetBusinessDetails$1.run(BusinessDetails.java:127)
10-27 16:39:28.834: E/AndroidRuntime(25260): at android.os.Handler.handleCallback(Handler.java:605)
10-27 16:39:28.834: E/AndroidRuntime(25260): at android.os.Handler.dispatchMessage(Handler.java:92)
10-27 16:39:28.834: E/AndroidRuntime(25260): at android.os.Looper.loop(Looper.java:137)
10-27 16:39:28.834: E/AndroidRuntime(25260): at android.app.ActivityThread.main(ActivityThread.java:4697)
10-27 16:39:28.834: E/AndroidRuntime(25260): at java.lang.reflect.Method.invokeNative(Native Method)
10-27 16:39:28.834: E/AndroidRuntime(25260): at java.lang.reflect.Method.invoke(Method.java:511)
10-27 16:39:28.834: E/AndroidRuntime(25260): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:787)
10-27 16:39:28.834: E/AndroidRuntime(25260): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)
10-27 16:39:28.834: E/AndroidRuntime(25260): at dalvik.system.NativeStart.main(Native Method)
And this is the ASYNC task that handles the networking:
class GetBusinessDetails extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(BusinessDetails.this);
pDialog.setMessage("Loading details. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
protected String doInBackground(String... params) {
runOnUiThread(new Runnable() {
public void run() {
int success;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("bid", bid));
JSONObject json = jsonParser.makeHttpRequest(
url_business_detials, "GET", params);
Log.d("Single Business Details", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
JSONArray businessObj = json.getJSONArray(TAG_BUSINESS); // JSON Array
JSONObject business = businessObj.getJSONObject(0);
TextView _bName = (TextView) findViewById(R.id.bnameInf);
TextView _phone = (TextView) findViewById(R.id.phoneInf);
TextView _address = (TextView) findViewById(R.id.addressInf);
TextView _city = (TextView) findViewById(R.id.cityInf);
TextView _state = (TextView) findViewById(R.id.stateInf);
TextView _zip = (TextView) findViewById(R.id.zipInf);
_bName.setText(business.getString(TAG_NAME));
_phone.setText(business.getString(TAG_PHONE));
_address.setText(business.getString(TAG_ADDRESS));
_city.setText(business.getString(TAG_CITY));
_state.setText(business.getString(TAG_STATE));
_zip.setText(business.getString(TAG_ZIP));
}else{
Toast.makeText(getApplicationContext(), "No Match Returned", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once got all details
pDialog.dismiss();
}
}
Without a stacktrace i would bet my money on 2 things:
in onCreate the Activity is still starting up and you already create a Toast
visual stuff is often better off with an Activity Context instead of the Appcontext
anyway, stacktrace would be nice
com.example.businesslookup.BusinessDetails$GetBusinessDetails$1.run(BusinessDetails.java:127)
in this line, there is your problem
also please read:
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
You are using an AsyncTask, but you're also wrapping your code in a call to runOnUiThread() which defeats the purpose of using an AsyncTask. Try removing this wrapper and moving the UI access to onPostExecute():
protected String doInBackground(String... params) {
int success;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("bid", bid));
JSONObject json = jsonParser.makeHttpRequest(
url_business_detials, "GET", params);
Log.d("Single Business Details", json.toString());
success = json.getInt(TAG_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
if (success == 1) {
JSONArray businessObj = json.getJSONArray(TAG_BUSINESS); // JSON Array
JSONObject business = businessObj.getJSONObject(0);
TextView _bName = (TextView) findViewById(R.id.bnameInf);
TextView _phone = (TextView) findViewById(R.id.phoneInf);
TextView _address = (TextView) findViewById(R.id.addressInf);
TextView _city = (TextView) findViewById(R.id.cityInf);
TextView _state = (TextView) findViewById(R.id.stateInf);
TextView _zip = (TextView) findViewById(R.id.zipInf);
_bName.setText(business.getString(TAG_NAME));
_phone.setText(business.getString(TAG_PHONE));
_address.setText(business.getString(TAG_ADDRESS));
_city.setText(business.getString(TAG_CITY));
_state.setText(business.getString(TAG_STATE));
_zip.setText(business.getString(TAG_ZIP));
}else{
Toast.makeText(getApplicationContext(), "No Match Returned", Toast.LENGTH_LONG).show();
}
}
(I don't know if exact this code will compile, but it's enough to give you the right idea.)

Categories

Resources