Unknown IllegalArgumentException text cannot be null - java

I'm receiving a weird IAE during one of my activities.
08-13 16:24:59.991: E/AndroidRuntime(924): FATAL EXCEPTION: main
08-13 16:24:59.991: E/AndroidRuntime(924): java.lang.IllegalArgumentException: text cannot be null
08-13 16:24:59.991: E/AndroidRuntime(924): at android.graphics.Paint.measureText(Paint.java:1281)
08-13 16:24:59.991: E/AndroidRuntime(924): at com.echo.holographlibrary.BarGraph.onDraw(BarGraph.java:151)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.view.View.draw(View.java:10880)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.view.ViewGroup.drawChild(ViewGroup.java:2899)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.view.ViewGroup.drawChild(ViewGroup.java:2897)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.view.View.draw(View.java:10883)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.widget.FrameLayout.draw(FrameLayout.java:450)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.widget.ScrollView.draw(ScrollView.java:1524)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.view.ViewGroup.drawChild(ViewGroup.java:2899)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.view.View.draw(View.java:10883)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.widget.FrameLayout.draw(FrameLayout.java:450)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.view.ViewGroup.drawChild(ViewGroup.java:2899)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.view.ViewGroup.drawChild(ViewGroup.java:2897)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2495)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.view.View.draw(View.java:10883)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.widget.FrameLayout.draw(FrameLayout.java:450)
08-13 16:24:59.991: E/AndroidRuntime(924): at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:2106)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.view.ViewRootImpl.draw(ViewRootImpl.java:2005)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1613)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2418)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.os.Handler.dispatchMessage(Handler.java:99)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.os.Looper.loop(Looper.java:137)
08-13 16:24:59.991: E/AndroidRuntime(924): at android.app.ActivityThread.main(ActivityThread.java:4340)
08-13 16:24:59.991: E/AndroidRuntime(924): at java.lang.reflect.Method.invokeNative(Native Method)
08-13 16:24:59.991: E/AndroidRuntime(924): at java.lang.reflect.Method.invoke(Method.java:511)
08-13 16:24:59.991: E/AndroidRuntime(924): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
08-13 16:24:59.991: E/AndroidRuntime(924): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
08-13 16:24:59.991: E/AndroidRuntime(924): at dalvik.system.NativeStart.main(Native Method)
08-13 16:29:41.041: I/Process(924): Sending signal. PID: 924 SIG: 9
This worked fine before but now that I've used some dynamic adding to xml, it seemed to have crashed. Below are the calls, and I've been unable to catch this exception.
package com.example.exercise;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Menu;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import com.echo.holographlibrary.Bar;
import com.echo.holographlibrary.BarGraph;
public class GraphDetail extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_graph_detail);
try{
boolean done = false;
int begin = 0;
int count = 4;
while(!done)
{
if(count>=MainActivity.test.size())
{
done = true;
break;
}
ArrayList<Bar> points = new ArrayList<Bar>();
Intent intent1 = getIntent();
int max = (intent1.getIntExtra("max", 0));
int[] weight = new int[MainActivity.test.size()];
for(int i=begin; i<count; i++)
{
weight[i] = MainActivity.test.get(i).getWeight();
}
String[] names = new String[MainActivity.test.size()];
for(int i = begin; i<count; i++)
{
names[i] = MainActivity.test.get(i).getName();
}
for(int i = 0; i< weight.length; i++)
{
Bar d = new Bar();
if(weight[i]!=max)
d.setColor(Color.parseColor("#99CC00"));
else
{
d.setColor(Color.parseColor("#FFBB33"));
}
d.setName(names[i]);
d.setValue(weight[i]);
points.add(d);
}
Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 130, r.getDisplayMetrics());
RelativeLayout rl = (RelativeLayout)findViewById(R.id.container);
int px1 = (int)px;
BarGraph bar = new BarGraph(this);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT,
px1);
bar.setBars(points);
bar.setUnit("0");
bar.appendUnit(true);
rl.addView(bar, lp);
begin+=count;
count+=3;
if(count>=MainActivity.test.size())
{
done = true;
break;
}
}
}
catch(Exception e)
{
e.printStackTrace();
}
// ArrayList<Bar> points = new ArrayList<Bar>();
// ArrayList<Bar> points1 = new ArrayList<Bar>();
// ArrayList<Bar> points2 = new ArrayList<Bar>();
// Intent intent1 = getIntent();
// int max = (intent1.getIntExtra("max",0));
// int[] weight = new int[MainActivity.test.size()];
// for(int i = 0; i<MainActivity.test.size(); i++)
// {
// weight[i] = MainActivity.test.get(i).getWeight();
// }
// String[] names = new String[MainActivity.test.size()];
// for(int i = 0; i<MainActivity.test.size(); i++)
// {
// names[i] = MainActivity.test.get(i).getName();
// }
// for(int i = 0; i< weight.length; i++)
// {
// Bar d = new Bar();
// if(weight[i]!=max)
// d.setColor(Color.parseColor("#99CC00"));
// else
// {
// d.setColor(Color.parseColor("#FFBB33"));
// }
//
// d.setName(names[i]);
// d.setValue(weight[i]);
// if(i<4)
// points.add(d);
// if(i>=4 && i<8)
// points1.add(d);
// if(i>=8)
// points2.add(d);
// }
// BarGraph g = (BarGraph) findViewById(R.id.graph);
// g.setBars(points);
// BarGraph g1 = (BarGraph) findViewById(R.id.graph1);
// g1.setBars(points1);
// BarGraph g2 = (BarGraph) findViewById(R.id.graph2);
// g2.setBars(points2);
// g.setUnit("0");
// g.appendUnit(true);
// g1.setUnit("0");
// g1.appendUnit(true);
// g2.setUnit("0");
// g2.appendUnit(true);
//
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.graph_detail, menu);
return true;
}
}

String[] names = new String[MainActivity.test.size()];
for(int i = begin; i<count; i++)
{
names[i] = MainActivity.test.get(i).getName();
}
...
d.setName(names[i]);
...
bar.setBars(points);
Have you checked the length of your names array versus count? It's likely that you are generating an array that is larger than the size of count, and because of that you're passing null later to d.setName, which ends up causing an exception later when calling bar.setBars.

Related

Getting Noclassdeffounderror on working with Google places API android

I am working on a tutorial found on this link:
http://www.androidhive.info/2012/08/android-working-with-google-places-and-maps-tutorial/
I am getting the following error on clicking the button:
08-13 12:28:03.226: E/AndroidRuntime(9180): FATAL EXCEPTION: main
08-13 12:28:03.226: E/AndroidRuntime(9180): java.lang.NoClassDefFoundError: com.androidhive.googleplacesandmaps.PlacesMapActivity
08-13 12:28:03.226: E/AndroidRuntime(9180): at com.androidhive.googleplacesandmaps.MainActivity$1.onClick(MainActivity.java:110)
08-13 12:28:03.226: E/AndroidRuntime(9180): at android.view.View.performClick(View.java:2538)
08-13 12:28:03.226: E/AndroidRuntime(9180): at android.view.View$PerformClick.run(View.java:9152)
08-13 12:28:03.226: E/AndroidRuntime(9180): at android.os.Handler.handleCallback(Handler.java:587)
08-13 12:28:03.226: E/AndroidRuntime(9180): at android.os.Handler.dispatchMessage(Handler.java:92)
08-13 12:28:03.226: E/AndroidRuntime(9180): at android.os.Looper.loop(Looper.java:130)
08-13 12:28:03.226: E/AndroidRuntime(9180): at android.app.ActivityThread.main(ActivityThread.java:3689)
08-13 12:28:03.226: E/AndroidRuntime(9180): at java.lang.reflect.Method.invokeNative(Native Method)
08-13 12:28:03.226: E/AndroidRuntime(9180): at java.lang.reflect.Method.invoke(Method.java:507)
08-13 12:28:03.226: E/AndroidRuntime(9180): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:842)
08-13 12:28:03.226: E/AndroidRuntime(9180): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
08-13 12:28:03.226: E/AndroidRuntime(9180): at dalvik.system.NativeStart.main(Native Method)
08-13 12:28:03.226: E/AndroidRuntime(9180): Caused by: java.lang.IllegalAccessError: Class ref in pre-verified class resolved to unexpected implementation
08-13 12:28:03.226: E/AndroidRuntime(9180): at dalvik.system.DexFile.defineClass(Native Method)
08-13 12:28:03.226: E/AndroidRuntime(9180): at dalvik.system.DexFile.loadClassBinaryName(DexFile.java:207)
08-13 12:28:03.226: E/AndroidRuntime(9180): at dalvik.system.PathClassLoader.findClass(PathClassLoader.java:200)
08-13 12:28:03.226: E/AndroidRuntime(9180): at java.lang.ClassLoader.loadClass(ClassLoader.java:551)
08-13 12:28:03.226: E/AndroidRuntime(9180): at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
08-13 12:28:03.226: E/AndroidRuntime(9180): ... 12 more
The placesmapactivity.java class is shown below:
package com.androidhive.googleplacesandmaps;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class PlacesMapActivity extends MapActivity {
// Nearest places
PlacesList nearPlaces;
// Map view
MapView mapView;
// Map overlay items
List<Overlay> mapOverlays;
AddItemizedOverlay itemizedOverlay;
GeoPoint geoPoint;
// Map controllers
MapController mc;
double latitude;
double longitude;
OverlayItem overlayitem;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_places);
// Getting intent data
Intent i = getIntent();
// Users current geo location
String user_latitude = i.getStringExtra("user_latitude");
String user_longitude = i.getStringExtra("user_longitude");
// Nearplaces list
nearPlaces = (PlacesList) i.getSerializableExtra("near_places");
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
// Geopoint to place on map
geoPoint = new GeoPoint((int) (Double.parseDouble(user_latitude) * 1E6),
(int) (Double.parseDouble(user_longitude) * 1E6));
// Drawable marker icon
Drawable drawable_user = this.getResources()
.getDrawable(R.drawable.mark_red);
itemizedOverlay = new AddItemizedOverlay(drawable_user, this);
// Map overlay item
overlayitem = new OverlayItem(geoPoint, "Your Location",
"That is you!");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
itemizedOverlay.populateNow();
// Drawable marker icon
Drawable drawable = this.getResources()
.getDrawable(R.drawable.mark_blue);
itemizedOverlay = new AddItemizedOverlay(drawable, this);
mc = mapView.getController();
// These values are used to get map boundary area
// The area where you can see all the markers on screen
int minLat = Integer.MAX_VALUE;
int minLong = Integer.MAX_VALUE;
int maxLat = Integer.MIN_VALUE;
int maxLong = Integer.MIN_VALUE;
// check for null in case it is null
if (nearPlaces.results != null) {
// loop through all the places
for (Place place : nearPlaces.results) {
latitude = place.geometry.location.lat; // latitude
longitude = place.geometry.location.lng; // longitude
// Geopoint to place on map
geoPoint = new GeoPoint((int) (latitude * 1E6),
(int) (longitude * 1E6));
// Map overlay item
overlayitem = new OverlayItem(geoPoint, place.name,
place.vicinity);
itemizedOverlay.addOverlay(overlayitem);
// calculating map boundary area
minLat = (int) Math.min( geoPoint.getLatitudeE6(), minLat );
minLong = (int) Math.min( geoPoint.getLongitudeE6(), minLong);
maxLat = (int) Math.max( geoPoint.getLatitudeE6(), maxLat );
maxLong = (int) Math.max( geoPoint.getLongitudeE6(), maxLong );
}
mapOverlays.add(itemizedOverlay);
// showing all overlay items
itemizedOverlay.populateNow();
}
// Adjusting the zoom level so that you can see all the markers on map
mapView.getController().zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
// Showing the center of the map
mc.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
mapView.postInvalidate();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
The button click code is shown below:
btnShowOnMap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(MainActivity.this,
PlacesMapActivity.class);
// Sending user current geo location
i.putExtra("user_latitude", Double.toString(gps.getLatitude()));
i.putExtra("user_longitude", Double.toString(gps.getLongitude()));
// passing near places to map activity
i.putExtra("near_places", nearPlaces);
// staring activity
startActivity(i);
}
});
}

My button works first time to work out the equation but not the 2nd time after a new number has been put in the edit text field

I am an enthusiastic newbie when it comes to coding so would really appreciate any help with my problem. I am designing a little math game where it generates a random number less than 11 and the user then puts a number in the edit text field presses the button. The idea is if the random number and the user input number equal 10 the user gets a point and if they get it marked wrong, then another randomly generated number appears for the user to continue the process.
My problem is that it seems to work the first time, then when the user enters a number for the second time and presses the button it crashes. Please excuse what must seem like messy coding to you professionals but a lot of tutorials and trial and error to get this far.
package com.example.mathtesttwo;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textOne = (TextView) findViewById(R.id.textView3);
textOne.setText("4");
final TextView guessText = (TextView) findViewById(R.id.textView2);
final EditText userGuess = (EditText) findViewById(R.id.editText1);
final TextView correctScore = (TextView) findViewById(R.id.textView1);
final TextView wrongScore = (TextView) findViewById(R.id.textView4);
wrongScore.setText("0");
////////////////////////
String randText = "";
Random randGen = new Random();
int rando = randGen.nextInt(11);
randText = Integer.toString(rando);
textOne.setText(randText);
/////////////////
Button pushMe = (Button) findViewById(R.id.button1);
pushMe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int userNumber = Integer.parseInt(userGuess.getText().toString());
int textNumber = Integer.parseInt(textOne.getText().toString());
int highScore = Integer.parseInt(correctScore.getText().toString());
int lowScore = Integer.parseInt(wrongScore.getText().toString());
if ( userNumber== 10 - textNumber) {
guessText.setText("you got it correct");
correctScore.setText("correct:" + highScore+1));
} else {
guessText.setText("WRONG");
wrongScore.setText("wrong:" + (lowScore+1));
}
String randText = "";
// TODO Auto-generated method stub
Random randGen = new Random();
int rando = randGen.nextInt(11);
randText = Integer.toString(rando);
textOne.setText(randText);
}
});
}
#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;
}
}
LOGCAT
03-28 15:24:19.314: D/AndroidRuntime(959): Shutting down VM
03-28 15:24:19.314: W/dalvikvm(959): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
03-28 15:24:19.484: E/AndroidRuntime(959): FATAL EXCEPTION: main
03-28 15:24:19.484: E/AndroidRuntime(959): java.lang.NumberFormatException: Invalid int: "correct:1"
03-28 15:24:19.484: E/AndroidRuntime(959): at java.lang.Integer.invalidInt(Integer.java:138)
03-28 15:24:19.484: E/AndroidRuntime(959): at java.lang.Integer.invalidInt(Integer.java:138)
03-28 15:24:19.484: E/AndroidRuntime(959): at java.lang.Integer.parseInt(Integer.java:366)
03-28 15:24:19.484: E/AndroidRuntime(959): at java.lang.Integer.parseInt(Integer.java:332)
03-28 15:24:19.484: E/AndroidRuntime(959): at com.example.mathtesttwo.MainActivity$1.onClick(MainActivity.java:55)
03-28 15:24:19.484: E/AndroidRuntime(959): at android.view.View.performClick(View.java:4240)
03-28 15:24:19.484: E/AndroidRuntime(959): at android.view.View$PerformClick.run(View.java:17721)
03-28 15:24:19.484: E/AndroidRuntime(959): at android.os.Handler.handleCallback(Handler.java:730)
03-28 15:24:19.484: E/AndroidRuntime(959): at android.os.Handler.dispatchMessage(Handler.java:92)
03-28 15:24:19.484: E/AndroidRuntime(959): at android.os.Looper.loop(Looper.java:137)
03-28 15:24:19.484: E/AndroidRuntime(959): at android.app.ActivityThread.main(ActivityThread.java:5103)
03-28 15:24:19.484: E/AndroidRuntime(959): at java.lang.reflect.Method.invokeNative(Native Method)
03-28 15:24:19.484: E/AndroidRuntime(959): at java.lang.reflect.Method.invoke(Method.java:525)
03-28 15:24:19.484: E/AndroidRuntime(959): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-28 15:24:19.484: E/AndroidRuntime(959): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-28 15:24:19.484: E/AndroidRuntime(959): at dalvik.system.NativeStart.main(Native Method)
Try this..
Remove below lines from OnClick
int highScore = Integer.parseInt(correctScore.getText().toString());
int lowScore = Integer.parseInt(wrongScore.getText().toString());
EDIT:
int highScore = 0;
if(correctScore.getText().toString().contains("correct") || correctScore.getText().toString().contains("wrong")){
String[] separated = correctScore.getText().toString().split(":");
highScore = Integer.parseInt(separated[1]);
}else{
highScore = Integer.parseInt(correctScore.getText().toString());
}
int lowScore = 0;
if(wrongScore.getText().toString().contains("correct") || wrongScore.getText().toString().contains("wrong")){
String[] separated = wrongScore.getText().toString().split(":");
lowScore = Integer.parseInt(separated[1]);
}else{
lowScore = Integer.parseInt(wrongScore.getText().toString());
}

CursorIndexOutOfBoundsException: Index 1 requested, with a size of 1. Error - Android

I'm working on Android application and when trying to get SQLite database data as TextView (only one record in the table) facing this error.
The log and exception:
03-28 01:37:22.137: E/AndroidRuntime(9585): FATAL EXCEPTION: main
03-28 01:37:22.137: E/AndroidRuntime(9585): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tourinfo/com.example.tourinfo.TourInfo}: android.database.CursorIndexOutOfBoundsException: Index 1 requested, with a size of 1
03-28 01:37:22.137: E/AndroidRuntime(9585): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
03-28 01:37:22.137: E/AndroidRuntime(9585): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
03-28 01:37:22.137: E/AndroidRuntime(9585): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
03-28 01:37:22.137: E/AndroidRuntime(9585): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
03-28 01:37:22.137: E/AndroidRuntime(9585): at android.os.Handler.dispatchMessage(Handler.java:99)
03-28 01:37:22.137: E/AndroidRuntime(9585): at android.os.Looper.loop(Looper.java:123)
03-28 01:37:22.137: E/AndroidRuntime(9585): at android.app.ActivityThread.main(ActivityThread.java:3683)
03-28 01:37:22.137: E/AndroidRuntime(9585): at java.lang.reflect.Method.invokeNative(Native Method)
03-28 01:37:22.137: E/AndroidRuntime(9585): at java.lang.reflect.Method.invoke(Method.java:507)
03-28 01:37:22.137: E/AndroidRuntime(9585): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-28 01:37:22.137: E/AndroidRuntime(9585): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-28 01:37:22.137: E/AndroidRuntime(9585): at dalvik.system.NativeStart.main(Native Method)
03-28 01:37:22.137: E/AndroidRuntime(9585): Caused by: android.database.CursorIndexOutOfBoundsException: Index 1 requested, with a size of 1
03-28 01:37:22.137: E/AndroidRuntime(9585): at android.database.AbstractCursor.checkPosition(AbstractCursor.java:580)
03-28 01:37:22.137: E/AndroidRuntime(9585): at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:214)
03-28 01:37:22.137: E/AndroidRuntime(9585): at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:41)
03-28 01:37:22.137: E/AndroidRuntime(9585): at com.example.tourinfo.TourInfo.onCreate(TourInfo.java:44)
03-28 01:37:22.137: E/AndroidRuntime(9585): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-28 01:37:22.137: E/AndroidRuntime(9585): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
03-28 01:37:22.137: E/AndroidRuntime(9585): ... 11 more
This is the java code:
public class TourInfo extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tour_info);
TourInfoDatabaseHelper jobInfoDatabaseHelper = new TourInfoDatabaseHelper(this);
Cursor cursorJObInfo = jobInfoDatabaseHelper.getAllJobInfoRecords();
if(cursorJObInfo.moveToFirst()){
do{
String startLocation = cursorJObInfo.getString(1);
String endLocation = cursorJObInfo.getString(2);
String type = cursorJObInfo.getString(3);
Log.d("DB value", startLocation +" "+ endLocation +" "+ type);
}while(cursorJObInfo.moveToNext());
}
// if(!cursorJObInfo.isClosed()){
// cursorJObInfo.close();
// }
TextView startLocationView = (TextView) findViewById(R.id.start_location_view);
startLocationView.setText(cursorJObInfo.getString(1));
TextView endLocationView = (TextView) findViewById(R.id.end_location_view);
endLocationView.setText(cursorJObInfo.getString(2));
TextView typeOfJourneyView = (TextView) findViewById(R.id.type_of_journey_view);
typeOfJourneyView.setText(cursorJObInfo.getString(3));
}
public void onClickedLocations(View view){
Intent intent = new Intent(this, LocationList.class);
startActivity(intent);
}
}
TourInfoDatabaseHelper.java class
public class TourInfoDatabaseHelper {
// private static final int DATABASE_VERSION= 2;
// private static final String DATABASE_NAME = "tourinfo.db";
private static final String TABLE_NAME = "tour_info_details";
public static final String JOBINFO_COLUMN_JOB_ID = "job_id";
public static final String JOBINFO_COLUMN_START_LOCATION = "start_location";
public static final String JOBINFO_COLUMN_END_LOCATION = "end_location";
public static final String JOBINFO_COLUMN_TYPE = "type";
public static final String JOBINFO_COLUMN_TOUR_NUMBER = "tour_number";
public static final String JOBINFO_COLUMN_USER_ID ="user_id";
private SQLiteDatabase jobInfoDatabase;
private JobInfoOpenHelper jobInfoOpenHelper;
public TourInfoDatabaseHelper (Context context) {
jobInfoOpenHelper = new JobInfoOpenHelper(context);
jobInfoDatabase = jobInfoOpenHelper.getWritableDatabase();
}
public void saveJobInfoRecords (String startLocation,String endLocation,String type,String tourNumber,int userId){
ContentValues contentValues = new ContentValues();
// contentValues.put(JOBINFO_COLUMN_JOB_ID, jobId);
contentValues.put(JOBINFO_COLUMN_START_LOCATION, startLocation);
contentValues.put(JOBINFO_COLUMN_END_LOCATION, endLocation);
contentValues.put(JOBINFO_COLUMN_TYPE, type);
contentValues.put(JOBINFO_COLUMN_TOUR_NUMBER, tourNumber);
contentValues.put(JOBINFO_COLUMN_USER_ID, userId);
jobInfoDatabase.insert(TABLE_NAME, null, contentValues);
}
public Cursor getAllJobInfoRecords(){
return jobInfoDatabase.rawQuery(" SELECT * FROM " + TABLE_NAME, null);
}
private class JobInfoOpenHelper extends SQLiteOpenHelper {
JobInfoOpenHelper(Context context) {
super(context,MainDBAdapter.DATABASE_NAME,null,MainDBAdapter.DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase jobInfoDatabase) {
}
#Override
public void onUpgrade(SQLiteDatabase jobInfoDatabase, int oldVersion, int newVersion) {
// jobInfoDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
// onCreate(jobInfoDatabase);
}
}
}
Please help me for avoid this error.
You loop through your cursor in the do-while loop but access cursor data with getString() after it, when the cursor is pointing after the last result row.
It's a little unclear what you want to do: You're fetching all records but are only using one result row. As a quick fix, capture the values inside the do-while and not after, e.g.
String startLocation = null;
String endLocation = null;
String type = null;
if(cursorJObInfo.moveToFirst()){
do{
startLocation = cursorJObInfo.getString(1);
endLocation = cursorJObInfo.getString(2);
type = cursorJObInfo.getString(3);
Log.d("DB value", startLocation +" "+ endLocation +" "+ type);
}while(cursorJObInfo.moveToNext());
}
// ...
startLocationView.setText(startLocation); // instead of calling getString() on the cursor here
// the same for the other textviews
Check whether there is data available in the table.
This Cursor cursorJObInfo = jobInfoDatabaseHelper.getAllJobInfoRecords(); is NULL because there is probably no data in the table.

Update and remove GridView items at runtime

i am developing a project where i compare the images of two items,So if two items will have same image after clicking these items should be hide. my code is given below and this code encounter a problem. is this a logical error or any other issue? i try to solve the issue but did't resolve.. Please guide me... here is my main Activity.
MainActivity.java
public class MainActivity extends Activity {
Context ctx;
int imagesArray[];
ImageAdapter adapter;
List<Integer> pictures;
boolean flage = false;
GridView gridView;
int save1, save2;
int img1 = -1, img2 = -1;
public int OriginalArray[] = { R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_0,
R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3 };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageView myimage = new ImageView(ctx);
gridView = (GridView) findViewById(R.id.gv_memory);
gridView.setAdapter(adapter);
shuffleArray();
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
myimage.setImageResource(pictures.get(position));
if (flage == false) {
img1 = pictures.get(position);
flage = true;
} else if (flage == true) {
img2 = pictures.get(position);
checkResult();
flage = false;
}
}
private void checkResult() {
// TODO Auto-generated method stub
if (img1 == img2) {
adapter.pictureList.remove(img1);
adapter.pictureList.remove(img2);
adapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "Congratualatin !!!!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Sorry!!!!",
Toast.LENGTH_LONG).show();
}
}
});
}
private void shuffleArray() {
// TODO Auto-generated method stub
pictures = new ArrayList<Integer>();
for (int index = 0; index < OriginalArray.length; index++) {
pictures.add(OriginalArray[index]);
}
Collections.shuffle(pictures);
}
}
ImageAdapter.java
public class ImageAdapter extends BaseAdapter {
private Context context;
List<Integer> pictureList = new ArrayList<Integer>();
public ImageAdapter(Context c) {
context = c;
for (int i = 0; i < 8; i++) {
pictureList.add(R.drawable.question);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return (pictureList.size());
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return pictureList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView myimage = new ImageView(context);
myimage.setImageResource(pictureList.get(position));
myimage.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
myimage.setLayoutParams(new GridView.LayoutParams(70, 70));
return myimage;
}
}
LogCat.
03-14 06:09:03.793: D/dalvikvm(2877): GC_FOR_ALLOC freed 54K, 8% free 2771K/2996K, paused 111ms, total 117ms
03-14 06:09:03.802: I/dalvikvm-heap(2877): Grow heap (frag case) to 3.943MB for 1127536-byte allocation
03-14 06:09:03.922: D/dalvikvm(2877): GC_FOR_ALLOC freed 2K, 6% free 3870K/4100K, paused 118ms, total 118ms
03-14 06:09:03.962: D/AndroidRuntime(2877): Shutting down VM
03-14 06:09:03.962: W/dalvikvm(2877): threadid=1: thread exiting with uncaught exception (group=0x41465700)
03-14 06:09:03.972: E/AndroidRuntime(2877): FATAL EXCEPTION: main
03-14 06:09:03.972: E/AndroidRuntime(2877): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.memory/com.example.memory.MainActivity}: java.lang.NullPointerException
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.os.Handler.dispatchMessage(Handler.java:99)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.os.Looper.loop(Looper.java:137)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread.main(ActivityThread.java:5103)
03-14 06:09:03.972: E/AndroidRuntime(2877): at java.lang.reflect.Method.invokeNative(Native Method)
03-14 06:09:03.972: E/AndroidRuntime(2877): at java.lang.reflect.Method.invoke(Method.java:525)
03-14 06:09:03.972: E/AndroidRuntime(2877): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-14 06:09:03.972: E/AndroidRuntime(2877): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-14 06:09:03.972: E/AndroidRuntime(2877): at dalvik.system.NativeStart.main(Native Method)
03-14 06:09:03.972: E/AndroidRuntime(2877): Caused by: java.lang.NullPointerException
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.view.ViewConfiguration.get(ViewConfiguration.java:318)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.view.View.<init>(View.java:3264)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.widget.ImageView.<init>(ImageView.java:112)
03-14 06:09:03.972: E/AndroidRuntime(2877): at com.example.memory.MainActivity.onCreate(MainActivity.java:33)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.Activity.performCreate(Activity.java:5133)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
03-14 06:09:03.972: E/AndroidRuntime(2877): ... 11 more
03-14 06:14:04.503: I/Process(2877): Sending signal. PID: 2877 SIG: 9
You have
final ImageView myimage = new ImageView(ctx);
ctz is not initialized. Its only declared as Context ctx;
You have this
gridView.setAdapter(adapter);
But you need to intialize adapter before using the same
So change to
setContentView(R.layout.main);
final ImageView myimage = new ImageView(this); //this refers to Activity context
gridView = (GridView) findViewById(R.id.gv_memory);
adapter = new ImageAdapter(this)
gridView.setAdapter(adapter);

Use My location Latitude Longitude and DB Latitude Longitude Calculation Distance

Use My location Latitude Longitude and DB Latitude Longitude Calculation Distance.but always error "The application AndroidGoogleMaps(process com.androidhive.googlemaps)has stopped unexpectedly.Please try again."
public class AndroidGoogleMapsActivity extends MapActivity {
public int mm[][]= new int[100][100];
double[][] rtdist= new double[50][2];
double[][] okdist= new double[50][2];
public GeoPoint[] endpp = new GeoPoint[100];
private static String KEY_SUCCESS = "success";
private MyLocationOverlay mylayer;
private MapController mapController;
private MapView mapView;
protected GeoPoint geoPoint;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViews();
setupMap();
}
private void findViews() {
mapView = (MapView) findViewById(R.id.mapView);
mapController = mapView.getController();
mapView.setBuiltInZoomControls(true);
}
private void setupMap() {
List<Overlay> overlays = mapView.getOverlays();
mylayer = new MyLocationOverlay(this, mapView);
mylayer.runOnFirstFix(new Runnable() {
public void run() {
// Zoom in to current location
mapView.setTraffic(true);
mapController.setZoom(17);
mapController.animateTo(mylayer.getMyLocation());
}
});
overlays.add(mylayer);
GeoPoint startpp = mylayer.getMyLocation();
String b="SELECT lat,lng FROM markers";
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.execqlcmd(b);
try {
if (json.getString(KEY_SUCCESS) != null)
{
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1)
{
for(int i=0 ; i<100 ; i++) {
JSONObject json_row = json.getJSONObject("r"+i);
mm[i][0]=(int)(Double.parseDouble(json_row.getString("c0")) * 1E6) ;
mm[i][1]=(int)(Double.parseDouble(json_row.getString("c1")) * 1E6) ;
endpp[i] =new GeoPoint(mm[i][0], mm[i][1] );
MapController mc = mapView.getController();
DistanceCalculator caldist= new DistanceCalculator(6371);
for(int j = 0; j < 2; j++)
{
rtdist[j][0]=1;
rtdist[j][1]=caldist.CalculationByDistance(startpp, endpp[j]);
//startpp The location of the phone is
//endpp DB's lat lng
//To judge the results of this array is in line with the distance required by the user
if(rtdist[j][1]<=50)
{
okdist[j][0]=rtdist[j][0]; //The amount of store
okdist[j][0]=rtdist[j][1]; //Store the distance
}
}
mc.animateTo(geoPoint);
mc.setZoom(15);
mapView.invalidate();
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.mark_red);
AddItemizedOverlay itemizedOverlay =
new AddItemizedOverlay(drawable, this);
OverlayItem overlayitem = new OverlayItem(geoPoint, "Hello", "Sample Overlay item");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
}}}}
catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mylayer.enableMyLocation();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mylayer.disableMyLocation();
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
public class DistanceCalculator {
private double Radius;
// R = earth's radius (mean radius = 6,371km)
// Constructor
DistanceCalculator(double R) {
Radius = R;
}
public double CalculationByDistance(GeoPoint startpp, GeoPoint endpp) {
double lat1 = startpp.getLatitudeE6()/1E6;
double lat2 = endpp.getLatitudeE6()/1E6;
double lon1 = startpp.getLongitudeE6()/1E6;
double lon2 = endpp.getLongitudeE6()/1E6;
double dLat = Math.toRadians(lat2-lat1);
double dLon = Math.toRadians(lon2-lon1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2);
double c = 2 * Math.asin(Math.sqrt(a));
return Radius * c;
}
}
}
LogCat :
05-13 14:49:44.703: D/dalvikvm(303): GC_FOR_MALLOC freed 4358 objects / 275032 bytes in 316ms
05-13 14:49:44.903: D/dalvikvm(303): GC_FOR_MALLOC freed 10567 objects / 641664 bytes in 58ms
05-13 14:49:45.063: D/dalvikvm(303): GC_FOR_MALLOC freed 4727 objects / 310440 bytes in 45ms
05-13 14:49:45.243: D/dalvikvm(303): GC_FOR_MALLOC freed 6480 objects / 394584 bytes in 48ms
05-13 14:49:45.443: D/dalvikvm(303): GC_FOR_MALLOC freed 7949 objects / 616640 bytes in 51ms
05-13 14:49:45.623: D/dalvikvm(303): GC_FOR_MALLOC freed 6072 objects / 370040 bytes in 51ms
05-13 14:49:45.813: D/dalvikvm(303): GC_FOR_MALLOC freed 4449 objects / 354128 bytes in 62ms
05-13 14:49:45.823: I/dalvikvm-heap(303): Grow heap (frag case) to 3.048MB for 87396-byte allocation
05-13 14:49:45.884: D/dalvikvm(303): GC_FOR_MALLOC freed 45 objects / 2392 bytes in 66ms
05-13 14:49:45.953: D/dalvikvm(303): GC_FOR_MALLOC freed 2 objects / 80 bytes in 67ms
05-13 14:49:45.953: I/dalvikvm-heap(303): Grow heap (frag case) to 3.129MB for 87396-byte allocation
05-13 14:49:46.013: D/dalvikvm(303): GC_FOR_MALLOC freed 0 objects / 0 bytes in 58ms
05-13 14:49:46.273: E/JSON(303): {"tag":"exesqlcmd","success":1,"error":0,"rownum":2,"colnum":2,"r0":{"c0":"23.973728","c1":"121.583641"},"r1":{"c0":"23.973827","c1":"121.585625"}}
05-13 14:49:46.293: D/AndroidRuntime(303): Shutting down VM
05-13 14:49:46.293: W/dalvikvm(303): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
05-13 14:49:46.313: E/AndroidRuntime(303): FATAL EXCEPTION: main
05-13 14:49:46.313: E/AndroidRuntime(303): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidhive.googlemaps/com.androidhive.googlemaps.AndroidGoogleMapsActivity}: java.lang.NullPointerException
05-13 14:49:46.313: E/AndroidRuntime(303): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.os.Handler.dispatchMessage(Handler.java:99)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.os.Looper.loop(Looper.java:123)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.app.ActivityThread.main(ActivityThread.java:4627)
05-13 14:49:46.313: E/AndroidRuntime(303): at java.lang.reflect.Method.invokeNative(Native Method)
05-13 14:49:46.313: E/AndroidRuntime(303): at java.lang.reflect.Method.invoke(Method.java:521)
05-13 14:49:46.313: E/AndroidRuntime(303): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
05-13 14:49:46.313: E/AndroidRuntime(303): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
05-13 14:49:46.313: E/AndroidRuntime(303): at dalvik.system.NativeStart.main(Native Method)
05-13 14:49:46.313: E/AndroidRuntime(303): Caused by: java.lang.NullPointerException
05-13 14:49:46.313: E/AndroidRuntime(303): at com.androidhive.googlemaps.AndroidGoogleMapsActivity$DistanceCalculator.CalculationByDistance(AndroidGoogleMapsActivity.java:178)
05-13 14:49:46.313: E/AndroidRuntime(303): at com.androidhive.googlemaps.AndroidGoogleMapsActivity.setupMap(AndroidGoogleMapsActivity.java:106)
05-13 14:49:46.313: E/AndroidRuntime(303): at com.androidhive.googlemaps.AndroidGoogleMapsActivity.onCreate(AndroidGoogleMapsActivity.java:41)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
05-13 14:49:46.313: E/AndroidRuntime(303): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
05-13 14:49:46.313: E/AndroidRuntime(303): ... 11 more
if you want to calculate distance between two geographic point you have to see those two methods in the Location Class
Location Class
you can use it like this:
Location locationA = new Location("point A");
locationA.setLatitude(latA);
locationA.setLongitude(lngA);
Location locationB = new Location("point B");
locationB.setLatitude(latB);
LocationB.setLongitude(lngB);
distance = locationA.distanceTo(locationB);

Categories

Resources