So here my problem i'm setting the onitemclicklistener on listview1 and making it that if an item already exist on the order list, then the quantity will increment, but my problem is my program keep crashing
Here's my code
MainActivity.java
public class MainActivity extends Activity {
Database helper;
ListView lv,lv2;
ArrayAdapter<PostItemList> adapter;
ArrayAdapter<PostInventory> adapterInventory;
ArrayAdapter<PostOrder> adapterOrder;
ArrayList<PostItemList> list;
ArrayList<PostInventory> listInventory;
ArrayList<PostOrder> listorder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper = new Database(MainActivity.this);
lv = (ListView)findViewById(R.id.itemList);
lv2 = (ListView)findViewById(R.id.orderList);
list = helper.getAllData();
adapter = new PostAdapterItemList(MainActivity.this,list);
lv.setAdapter(adapter);
listorder = new ArrayList<PostOrder>();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,final int pos,
long arg3) {
// TODO Auto-generated method stub
PostItemList getData = list.get(pos);
String parseData = getData.toStringOrder();
String name[] = parseData.split(",");
int itemQuantity = Integer.parseInt(name[1]);
double itemPrice = Double.parseDouble(name[2]);
if (itemQuantity == 0){
String output = name[0] + " is out of stock.";
Toast.makeText(getBaseContext(), output, Toast.LENGTH_LONG).show();
} else {
itemQuantity = itemQuantity - 1;
String newQuantity = String.valueOf(itemQuantity);
helper.updateQuantity(name[0], newQuantity);
list.clear();
list = helper.getAllData();
adapter = new PostAdapterItemList(MainActivity.this, list);
lv.setAdapter(adapter);
int checker = 0;
if (listorder.isEmpty()){
listorder.add(new PostOrder(name[0], "1", name[2]));
adapterOrder = new PostAdapterOrder(MainActivity.this,listorder);
lv2.setAdapter(adapterOrder);
} else if (listorder.size()>0){
for(PostOrder order : listorder){
if (name[0].contentEquals(order.getItemName())){
String quantity = order.getItemQuantity();
order.setItemQuantity(String.valueOf((Integer.parseInt(quantity))+1));
adapterOrder.notifyDataSetChanged();
} else {
checker = 1;
}
}
}
if (checker==1){
listorder.add(new PostOrder(name[0], "1", name[1]));
adapterOrder = new PostAdapterOrder(MainActivity.this, listorder);
lv2.setAdapter(adapterOrder);
}
}
}
});
}
Logcat
10-11 00:05:13.190: D/dalvikvm(854): GC_FOR_ALLOC freed 57K, 5% free 3034K/3176K, paused 32ms, total 33ms
10-11 00:05:13.190: I/dalvikvm-heap(854): Grow heap (frag case) to 3.646MB for 635812-byte allocation
10-11 00:05:13.290: D/dalvikvm(854): GC_FOR_ALLOC freed 0K, 4% free 3655K/3800K, paused 22ms, total 22ms
10-11 00:05:13.870: I/Choreographer(854): Skipped 73 frames! The application may be doing too much work on its main thread.
10-11 00:05:13.950: D/gralloc_goldfish(854): Emulator without GPU emulation detected.
10-11 00:05:14.230: I/Choreographer(854): Skipped 37 frames! The application may be doing too much work on its main thread.
10-11 00:05:20.070: D/AndroidRuntime(854): Shutting down VM
10-11 00:05:20.070: W/dalvikvm(854): threadid=1: thread exiting with uncaught exception (group=0xb3a67ba8)
10-11 00:05:20.080: E/AndroidRuntime(854): FATAL EXCEPTION: main
10-11 00:05:20.080: E/AndroidRuntime(854): Process: com.example.posv3, PID: 854
10-11 00:05:20.080: E/AndroidRuntime(854): java.util.ConcurrentModificationException
10-11 00:05:20.080: E/AndroidRuntime(854): at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:573)
10-11 00:05:20.080: E/AndroidRuntime(854): at com.example.posv3.MainActivity$1.onItemClick(MainActivity.java:71)
10-11 00:05:20.080: E/AndroidRuntime(854): at android.widget.AdapterView.performItemClick(AdapterView.java:299)
10-11 00:05:20.080: E/AndroidRuntime(854): at android.widget.AbsListView.performItemClick(AbsListView.java:1113)
10-11 00:05:20.080: E/AndroidRuntime(854): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2904)
10-11 00:05:20.080: E/AndroidRuntime(854): at android.widget.AbsListView$3.run(AbsListView.java:3638)
10-11 00:05:20.080: E/AndroidRuntime(854): at android.os.Handler.handleCallback(Handler.java:733)
10-11 00:05:20.080: E/AndroidRuntime(854): at android.os.Handler.dispatchMessage(Handler.java:95)
10-11 00:05:20.080: E/AndroidRuntime(854): at android.os.Looper.loop(Looper.java:136)
10-11 00:05:20.080: E/AndroidRuntime(854): at android.app.ActivityThread.main(ActivityThread.java:5017)
10-11 00:05:20.080: E/AndroidRuntime(854): at java.lang.reflect.Method.invokeNative(Native Method)
10-11 00:05:20.080: E/AndroidRuntime(854): at java.lang.reflect.Method.invoke(Method.java:515)
10-11 00:05:20.080: E/AndroidRuntime(854): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
10-11 00:05:20.080: E/AndroidRuntime(854): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
10-11 00:05:20.080: E/AndroidRuntime(854): at dalvik.system.NativeStart.main(Native Method)
If you want to remove item from your iteration
for(Iterator<MyAdapter> it = result.iterator(); it.hasNext();) {
MyAdapter s = it.next();
if(s.getClientPoints().getPointsSpent() == 0) {
it.remove();
}
}
Sir Himanshu Agarwal, thanks for helping me. i solve the problem and heres my solution for the items thats is listed when it is already present on the list
for(PostOrder order : listorder){
if (name[0].contentEquals(order.getItemName())){
String quantity = order.getItemQuantity();
order.setItemQuantity(String.valueOf((Integer.parseInt(quantity))+1));
adapterOrder.notifyDataSetChanged();
break;
} else {
counter++;
}
}
}
if (counter == listorder.size()){
listorder.add(new PostOrder(name[0], "1", name[1]));
adapterOrder = new PostAdapterOrder(MainActivity.this, listorder);
lv2.setAdapter(adapterOrder);
}
Related
I am trying to use Voice Recognition on Android. Following is my code.
This is the code of the Button that is responsible to start speech recognition.
speak.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "City Name Please?");
startActivityForResult(intent, REQUEST_CODE);
}});
Here is a onActivityResult method.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
ArrayList<String> matches_Text = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
Log.v("Results", matches_Text.get(0).toString());
//Update EditText cityname here
String normalized_cityname = matches_Text.get(0).toString().trim();
normalized_cityname = normalized_cityname.replace(" ","%20");
try {
getResponseString("http://api.openweathermap.org/data/2.5/weather?q="+normalized_cityname+"&units=metric", true);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
The code worked ok but there are two problems I am encountering now and I am afraid that they may be related.
If I try to update text in an EditText instance cityname using cityname.setText(matches_Text.get(0).toString()), it crashes the app.
If I hit the speak button now, the google voice dialog comes up but shows can't reacg google at the moment.
Please suggest what can I do?
Adding the getResponseString method also.
public void getResponseString(String Url, boolean IsCalledOnVoiceInput) throws IOException, JSONException {
String temperature="";
String city;
String country;
String weather_main, weather_description;
MyAsyncTask xxx = new MyAsyncTask();
try {
String responseString = xxx.execute(Url).get();
TextView txtTemp = (TextView)findViewById(R.id.txt_temp);
TextView txtCity = (TextView)findViewById(R.id.txt_CityName);
TextView txtWeatherMain = (TextView)findViewById(R.id.textView2);
TextView txtWeatherDescription = (TextView)findViewById(R.id.textView3);
JSONObject reader = new JSONObject(responseString);
JSONObject main = reader.getJSONObject("main");
temperature = main.getString("temp");
Log.v("temperarure",temperature);
city = reader.getString("name");
Log.v("city",city);
JSONObject sys = reader.getJSONObject("sys");
country = sys.getString("country");
Log.v("country",country);
JSONArray weather = reader.getJSONArray("weather");
JSONObject weather_obj = weather.getJSONObject(0);
weather_main = weather_obj.getString("main");
weather_description = weather_obj.getString("description");
txtTemp.setText(temperature+" °C");
txtCity.setText(city+" ("+country+")");
txtWeatherMain.setText(weather_main);
txtWeatherDescription.setText(weather_description);
if(IsCalledOnVoiceInput)
Speak_Weather_Data(city,temperature,weather_main,weather_description);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e){
e.printStackTrace();
}
}
Here is the log output
12-24 13:36:06.050 12164-12164/samarth.learning.http D/dalvikvm﹕ Late-enabling CheckJNI
12-24 13:36:06.300 12164-12164/samarth.learning.http D/Network﹕ Network
12-24 13:36:06.300 12164-12164/samarth.learning.http V/Lat﹕ 28.8331443
12-24 13:36:06.300 12164-12164/samarth.learning.http V/Long﹕ 78.7717138
12-24 13:36:06.360 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libEGL_adreno.so
12-24 13:36:06.370 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libGLESv1_CM_adreno.so
12-24 13:36:06.380 12164-12164/samarth.learning.http D/libEGL﹕ loaded /vendor/lib/egl/libGLESv2_adreno.so
12-24 13:36:06.380 12164-12164/samarth.learning.http I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build: (CL4169980)
OpenGL ES Shader Compiler Version: 17.01.10.SPL
Build Date: 11/04/13 Mon
Local Branch:
Remote Branch:
Local Patches:
Reconstruct Branch:
12-24 13:36:06.430 12164-12164/samarth.learning.http D/OpenGLRenderer﹕ Enabling debug mode 0
12-24 13:36:06.531 12164-12164/samarth.learning.http E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
12-24 13:36:06.531 12164-12164/samarth.learning.http E/SpannableStringBuilder﹕ SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length
12-24 13:36:08.232 12164-12164/samarth.learning.http W/IInputConnectionWrapper﹕ showStatusIcon on inactive InputConnection
12-24 13:36:18.844 12164-12164/samarth.learning.http V/Results﹕ new delhi
12-24 13:36:18.844 12164-12164/samarth.learning.http D/AndroidRuntime﹕ Shutting down VM
12-24 13:36:18.844 12164-12164/samarth.learning.http W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x4157c8b0)
12-24 13:36:18.854 12164-12164/samarth.learning.http E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1234, result=-1, data=Intent { (has extras) }} to activity {samarth.learning.http/samarth.learning.http.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.deliverResults(ActivityThread.java:3462)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3505)
at android.app.ActivityThread.access$1100(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1346)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at samarth.learning.http.MainActivity.onActivityResult(MainActivity.java:160)
at android.app.Activity.dispatchActivityResult(Activity.java:5322)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3458)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3505)
at android.app.ActivityThread.access$1100(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1346)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:5225)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
12-24 13:36:22.558 12164-12164/samarth.learning.http I/Process﹕ Sending signal. PID: 12164 SIG: 9
is this what you mean?
i think matches_Text is sometimes NULL?! how about adding an
if(matches_Text == null){
Log.v("Results","matches_Text is NULL!");
return;
}
add above code just after ArrayList<String> matches_Text = da...
I have a method which converts an image into a round shape and sets it in an imageview. The method works properly in most of the cases, but misbehaves when images with certain resolutions are selected.
The method:
public void decodeImageFile(String imagePath, Matrix m){
// Will need to do DP to PX algorith herer
Bitmap bitmap = decodeSampleBitmapFromFile(imagePath, 1024, 1024);
//bitmap = Bitmap.createScaledBitmap(bitmap, 540, 960, true);
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Log.e("height", ""+h);
Log.e("width", ""+w);
//to prevent crashing the app as this is not a legal resolution
// if (h == 1920 && w == 2160) {
// bitmap = Bitmap.createScaledBitmap(bitmap, 540, 960, true);
// }
// logic to check whether the resulting image has a height or
// width greater than 0
if (bitmap.getWidth() > 0 && bitmap.getHeight() > 0) {
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);
bitmap = ImageController.transferSquare(bitmap);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
byteArray = baos.toByteArray();
bitmap = ImageController.resizeToHighResolutionCircle(bitmap);
choosePhotoBtn.setBackgroundResource(R.drawable.add_detail_photo_opaq_xhdpi);
yourPhoto.setImageBitmap(Bitmap.createScaledBitmap(bitmap, yourPhoto.getWidth(), yourPhoto.getHeight(), false));
}
}
I have seen the crashes for the 1080x1920 and 1920x2160 resolutions. The logcat for 1080x1920 resolution:
12-02 13:26:57.255: D/dalvikvm(28494): GC_FOR_ALLOC freed 14357K, 28% free 37780K/52472K, paused 17ms, total 17ms
12-02 13:26:57.335: E/height(28494): 1080
12-02 13:26:57.335: E/width(28494): 1920
12-02 13:26:57.350: D/dalvikvm(28494): GC_FOR_ALLOC freed 93K, 21% free 41738K/52472K, paused 12ms, total 12ms
12-02 13:26:57.355: I/dalvikvm-heap(28494): Grow heap (frag case) to 46.646MB for 4147216-byte allocation
12-02 13:26:57.365: D/dalvikvm(28494): GC_FOR_ALLOC freed <1K, 19% free 45788K/56524K, paused 11ms, total 11ms
12-02 13:26:57.610: D/dalvikvm(28494): GC_FOR_ALLOC freed 9108K, 27% free 42971K/58508K, paused 14ms, total 14ms
12-02 13:26:57.635: D/dalvikvm(28494): GC_FOR_ALLOC freed 5156K, 22% free 43217K/54748K, paused 15ms, total 15ms
12-02 13:26:57.645: I/dalvikvm-heap(28494): Grow heap (frag case) to 48.585MB for 4665616-byte allocation
12-02 13:26:57.665: D/dalvikvm(28494): GC_FOR_ALLOC freed 0K, 20% free 47773K/59308K, paused 17ms, total 17ms
12-02 13:27:03.610: W/dalvikvm(29085): threadid=12: thread exiting with uncaught exception (group=0x41939c08)
12-02 13:27:03.610: E/AndroidRuntime(29085): FATAL EXCEPTION: Parse.initialize Disk Check & Starting Command Cache
12-02 13:27:03.610: E/AndroidRuntime(29085): Process: com.navitas.studystory, PID: 29085
12-02 13:27:03.610: E/AndroidRuntime(29085): java.lang.SecurityException: Unable to find app for caller android.app.ApplicationThreadProxy#43839f28 (pid=29085) when registering receiver android.content.IIntentReceiver$Stub$Proxy#42c70b60
12-02 13:27:03.610: E/AndroidRuntime(29085): at android.os.Parcel.readException(Parcel.java:1472)
12-02 13:27:03.610: E/AndroidRuntime(29085): at android.os.Parcel.readException(Parcel.java:1426)
12-02 13:27:03.610: E/AndroidRuntime(29085): at android.app.ActivityManagerProxy.registerReceiver(ActivityManagerNative.java:2551)
12-02 13:27:03.610: E/AndroidRuntime(29085): at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1821)
12-02 13:27:03.610: E/AndroidRuntime(29085): at android.app.ContextImpl.registerReceiver(ContextImpl.java:1789)
12-02 13:27:03.610: E/AndroidRuntime(29085): at android.app.ContextImpl.registerReceiver(ContextImpl.java:1783)
12-02 13:27:03.610: E/AndroidRuntime(29085): at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:479)
12-02 13:27:03.610: E/AndroidRuntime(29085): at com.parse.ConnectivityNotifier.tryToRegisterForNetworkStatusNotifications(ConnectivityNotifier.java:55)
12-02 13:27:03.610: E/AndroidRuntime(29085): at com.parse.ConnectivityNotifier.addListener(ConnectivityNotifier.java:34)
12-02 13:27:03.610: E/AndroidRuntime(29085): at com.parse.ParseCommandCache.<init>(ParseCommandCache.java:101)
12-02 13:27:03.610: E/AndroidRuntime(29085): at com.parse.Parse.getEventuallyQueue(Parse.java:527)
12-02 13:27:03.610: E/AndroidRuntime(29085): at com.parse.Parse$1.run(Parse.java:126)
12-02 13:27:03.680: W/ApplicationPackageManager(29098): getCSCPackageItemText()
12-02 13:27:03.780: D/dalvikvm(29098): GC_FOR_ALLOC freed 206K, 12% free 17072K/19260K, paused 18ms, total 19ms
12-02 13:27:03.795: I/dalvikvm-heap(29098): Grow heap (frag case) to 25.620MB for 7356976-byte allocation
12-02 13:27:03.815: D/dalvikvm(29098): GC_FOR_ALLOC freed 0K, 9% free 24257K/26448K, paused 17ms, total 17ms
12-02 13:27:03.845: E/Lifecycle(29098): The onCreate() event
12-02 13:27:03.845: E/Lifecycle(29098): The onStart() event
12-02 13:27:03.850: E/Lifecycle(29098): The onResume() event
12-02 13:27:03.940: D/OpenGLRenderer(29098): Enabling debug mode 0
12-02 13:27:33.950: E/Lifecycle(29098): The onPause() event
12-02 13:27:33.955: E/Lifecycle(29098): The onStop() event
Please tell me where I am going wrong? What is a miss?
Create Class
public class MyUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler {
#Override
public void uncaughtException(Thread thread, Throwable ex) {
if(ex.getClass().equals(OutOfMemoryError.class))
{
try {
android.os.Debug.dumpHprofData("/sdcard/dump.hprof");
}
catch (IOException e) {
e.printStackTrace();
}
}
ex.printStackTrace();
}
}
and then put the following code in mainActivity
Thread.currentThread().setDefaultUncaughtExceptionHandler(new MyUncaughtExceptionHandler());
Add android:largeHeap="true" to your applicaton tag in the manifest to be able to claim more memory and use multi-threading for heavy operations like this. An asynctask, the built in thread class for short term operations, would be perfect, though your GUI will still hang for a bit while it is waiting for the task to complete decoding.
How to write ASyncTasks
For example, a decoder task.
public class BitmapDecoderTask extends AsyncTask<File, Integer, Bitmap> {
protected Bitmap doInBackground(File... files) {
int count = files.length;
Bitmap fullImage = null;
for (int i = 0; i < count; i++) {
fullImage = BitmapFactory.decodeFile(files[i].getAbsolutePath());
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return fullImage;
}
protected void onProgressUpdate(Integer... progress) {
//setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
//showDialog("Downloaded " + result + " bytes");
}
}
After which you can just create one of these tasks, call execute on it and get() the result or if it's a write action, just let it run and finish whenever.
Do remember to recycle() your bitmaps to avoid unnecessary memory claiming.
i am developing a project where i compare two item images,So if two items will have same image after clicking these items it should be permanently delete from the GridView. my code is given below and this code encounter a problem. please any one help me.
MainActivity.java
public class MainActivity extends Activity {
Context ctx;
int imagesArray[];
GridViewContent adapter;
List<Integer> pictures, pictureList;
boolean flage = false;
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);
shuffleArray();
final GridView grid = (GridView) findViewById(R.id.gv_memory);
grid.setAdapter(new GridViewContent(this));
}
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);
}
public class GridViewContent extends BaseAdapter {
private Context context;
private List<Integer> pictureList = new ArrayList<Integer>();
public GridViewContent(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(final int position, final View arg1,
final ViewGroup arg2) {
// TODO Auto-generated method stub
final ImageView myimage = new ImageView(context);
myimage.setImageResource(pictureList.get(position));
// myimage.setImageResource(pictures.get(pictureArray[position]));
myimage.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
myimage.setLayoutParams(new GridView.LayoutParams(70, 70));
final GridView grid = (GridView) findViewById(R.id.gv_memory);
myimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
myimage.setImageResource(pictures.get(position));
// View v1 = new View(context);
if (flage == false) {
img1 = pictures.get(position);
// v1 = arg2.getChildAt(position);
save1 = position;
flage = true;
} else if (flage == true) {
img2 = pictures.get(position);
save2 = position;
checkResult(save1, save2);
flage = false;
}
// else if(f)
}
});
return myimage;
}
}
public void checkResult(int s1, int s2) {
if (img1 == img2) {
pictureList.remove(s1); //this is line no 116
pictureList.remove(s1);
adapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "Congratualatin !!!!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Sorry!!!!", Toast.LENGTH_LONG)
.show();
final GridView grid = (GridView) findViewById(R.id.gv_memory);
grid.setAdapter(new GridViewContent(this));
}
}
}
LogCat.
03-14 01:07:12.791: D/dalvikvm(1598): GC_FOR_ALLOC freed 38K, 7% free 2771K/2980K, paused 183ms, total 185ms
03-14 01:07:12.811: I/dalvikvm-heap(1598): Grow heap (frag case) to 3.943MB for 1127536-byte allocation
03-14 01:07:12.941: D/dalvikvm(1598): GC_FOR_ALLOC freed 2K, 6% free 3870K/4084K, paused 128ms, total 128ms
03-14 01:07:13.111: D/dalvikvm(1598): GC_FOR_ALLOC freed 4K, 5% free 4253K/4448K, paused 25ms, total 26ms
03-14 01:07:13.143: I/dalvikvm-heap(1598): Grow heap (frag case) to 5.688MB for 1440016-byte allocation
03-14 01:07:13.271: D/dalvikvm(1598): GC_FOR_ALLOC freed <1K, 4% free 5659K/5856K, paused 127ms, total 127ms
03-14 01:07:13.481: I/Choreographer(1598): Skipped 49 frames! The application may be doing too much work on its main thread.
03-14 01:07:13.571: D/gralloc_goldfish(1598): Emulator without GPU emulation detected.
03-14 01:08:36.011: D/dalvikvm(1598): GC_FOR_ALLOC freed 357K, 9% free 5587K/6116K, paused 34ms, total 35ms
03-14 01:08:36.021: I/dalvikvm-heap(1598): Grow heap (frag case) to 6.543MB for 971296-byte allocation
03-14 01:08:36.154: D/dalvikvm(1598): GC_FOR_ALLOC freed 1K, 8% free 6534K/7068K, paused 123ms, total 123ms
03-14 01:08:39.422: D/dalvikvm(1598): GC_FOR_ALLOC freed 2385K, 8% free 5419K/5876K, paused 76ms, total 78ms
03-14 01:08:39.492: D/dalvikvm(1598): GC_FOR_ALLOC freed 1K, 4% free 5654K/5876K, paused 40ms, total 41ms
03-14 01:08:41.352: D/AndroidRuntime(1598): Shutting down VM
03-14 01:08:41.352: W/dalvikvm(1598): threadid=1: thread exiting with uncaught exception (group=0x41465700)
03-14 01:08:41.532: E/AndroidRuntime(1598): FATAL EXCEPTION: main
03-14 01:08:41.532: E/AndroidRuntime(1598): java.lang.NullPointerException
03-14 01:08:41.532: E/AndroidRuntime(1598): at com.example.memoryforkids.MainActivity.checkResult(MainActivity.java:116)
03-14 01:08:41.532: E/AndroidRuntime(1598): at com.example.memoryforkids.MainActivity$GridViewContent$1.onClick(MainActivity.java:102)
03-14 01:08:41.532: E/AndroidRuntime(1598): at android.view.View.performClick(View.java:4240)
03-14 01:08:41.532: E/AndroidRuntime(1598): at android.view.View$PerformClick.run(View.java:17721)
03-14 01:08:41.532: E/AndroidRuntime(1598): at android.os.Handler.handleCallback(Handler.java:730)
03-14 01:08:41.532: E/AndroidRuntime(1598): at android.os.Handler.dispatchMessage(Handler.java:92)
03-14 01:08:41.532: E/AndroidRuntime(1598): at android.os.Looper.loop(Looper.java:137)
03-14 01:08:41.532: E/AndroidRuntime(1598): at android.app.ActivityThread.main(ActivityThread.java:5103)
03-14 01:08:41.532: E/AndroidRuntime(1598): at java.lang.reflect.Method.invokeNative(Native Method)
03-14 01:08:41.532: E/AndroidRuntime(1598): at java.lang.reflect.Method.invoke(Method.java:525)
03-14 01:08:41.532: E/AndroidRuntime(1598): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-14 01:08:41.532: E/AndroidRuntime(1598): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-14 01:08:41.532: E/AndroidRuntime(1598): at dalvik.system.NativeStart.main(Native Method)
main.xml
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gv_memory"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" >
</GridView>
Thanks in advance..
Ok so, I found the bug, you have defined the pictureList variable in two places, the one being initialized inside the adapter class is a local variable. When checkResult is called, it uses the pictureList variable belonging to the main activity class. Do the following:
1) Remove the local variable inside the adapter class.
2) Initialize the pictureList variable that has been defined in the activity class.
This fixes the error. Its working fine on my machine now!
Also, there are a lot of issues with the logic you are using, you will realize that once you fix this error.
I recently added a splash screen to my Android application to mask the loading of a JSON file, but my app crashes after finishing parsing. I've commented out and uncommented out code until I found the problematic segment, but I'm not sure why it isn't working.
The code works if I comment out the for loop from this code segment.
From MagazinePagesActivity.java:
public void loadItems() {
for (Item item : SplashActivity.downloadedItems) {
Post post = (Post) item;
for (String tag : post.tags) {
if (tag.equals(this.tag)) {
// loader.loadImage(magazine.imageURL, new
// SimpleImageLoadingListener());
Bundle bundle = new Bundle();
bundle.putString("title", post.title);
bundle.putString("article", post.article);
bundle.putString("imageURL", post.imageURL);
MagazineFragment cover = new MagazineFragment();
cover.setArguments(bundle);
coverAdapter.addNewItem(cover);
}
}
}
setContentView(vp);
}
At first, I thought it was because SplashActivity.downloadedItems wasn't properly defined, but it looks fine to me:
From SplashActivity.java:
public static ArrayList<Item> downloadedItems = new ArrayList<Item>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new RetreiveJSONTask() {
protected void onPostExecute(String JSON)
{
Log.d("SplashActivity", "Beginning parsingJSON" );
downloadedItems = parseJSON ( JSON );
Log.d("SplashActivity", "Finished parsingJSON" );
Log.d("SplashActivity", "" + SplashActivity.downloadedItems.isEmpty());
Intent i = new Intent(SplashActivity.this, MagazinePagesActivity.class);
startActivity(i);
// Closes the splash screen
finish();
}
}.execute(sourceURL());
}
From LogCat:
10-16 19:23:12.602: D/AndroidRuntime(828): Shutting down VM
10-16 19:23:12.602: W/dalvikvm(828): threadid=1: thread exiting with uncaught exception (group=0x41465700)
10-16 19:23:12.632: E/AndroidRuntime(828): FATAL EXCEPTION: main
10-16 19:23:12.632: E/AndroidRuntime(828): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bruinfootball/com.dailybruin.bruinframework.channels.StoryListActivity}: java.lang.NullPointerException
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.os.Handler.dispatchMessage(Handler.java:99)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.os.Looper.loop(Looper.java:137)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread.main(ActivityThread.java:5103)
10-16 19:23:12.632: E/AndroidRuntime(828): at java.lang.reflect.Method.invokeNative(Native Method)
10-16 19:23:12.632: E/AndroidRuntime(828): at java.lang.reflect.Method.invoke(Method.java:525)
10-16 19:23:12.632: E/AndroidRuntime(828): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-16 19:23:12.632: E/AndroidRuntime(828): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-16 19:23:12.632: E/AndroidRuntime(828): at dalvik.system.NativeStart.main(Native Method)
10-16 19:23:12.632: E/AndroidRuntime(828): Caused by: java.lang.NullPointerException
10-16 19:23:12.632: E/AndroidRuntime(828): at com.dailybruin.bruinframework.channels.StoryListActivity.loadItems(StoryListActivity.java:27)
10-16 19:23:12.632: E/AndroidRuntime(828): at com.dailybruin.bruinframework.channels.JSONItemsActivity.onCreate(JSONItemsActivity.java:20)
10-16 19:23:12.632: E/AndroidRuntime(828): at com.dailybruin.bruinframework.channels.StoryItemsActivity.onCreate(StoryItemsActivity.java:18)
10-16 19:23:12.632: E/AndroidRuntime(828): at com.dailybruin.bruinframework.channels.StoryListActivity.onCreate(StoryListActivity.java:18)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.Activity.performCreate(Activity.java:5133)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
10-16 19:23:12.632: E/AndroidRuntime(828): ... 11 more
Not sure if it helps, but both SplashActivity and MagazinePagesActivity extend JSONItemsActivity, separately.
Thanks in advance for any help! I'm fairly new to Android, so please bear with me.
Edit: That's odd, the debug statement I put to check if the ArrayList is empty returns true, but another debug statement within parseJSON shows that things are being added. My parseJSON method:
public ArrayList<Item> parseJSON(String jsonString) {
ArrayList<Item> magazines = new ArrayList<Item>();
JSONArray jArray;
try {
jArray = new JSONArray(jsonString);
JSONObject jObject;
JSONObject image;
String img;
String title;
String subtitle;
int commentCount;
String content;
String date;
String ID;
String slug;
JSONArray array;
String[] tags;
for (int i = 0; i < jArray.length(); i++) {
jObject = jArray.getJSONObject(i);
img = jObject.getString("tall_image_url");
if (img.equals(""))
img = jObject.getString("image_url");
if (img.equals("") && !jObject.isNull("poster_image")) {
image = jObject.getJSONObject("poster_image");
img = image.getString("name");
}
title = jObject.getString("title");
subtitle = jObject.getString("subtitle");
commentCount = jObject.getInt("comment_count");
content = jObject.getString("content_html");
date = jObject.getString("creation_date");
ID = jObject.getString("id");
slug = jObject.getString("slug");
array = jObject.getJSONArray("tags_list");
tags = new String[array.length()];
for (int j = 0; j < array.length(); j++) {
tags[j] = array.getString(j);
}
for (String tag : tags) {
if (tag.equals(this.tag))
{
Post additive = new Post(img, title, subtitle,
commentCount, content, date, ID, slug, tags);
magazines.add(additive);
Log.d("SplashActivity", additive.toString());
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return magazines;
}
StoryListActivity line 27:
public void loadItems() {
(findViewById(R.id.progress_bar)).setVisibility(View.GONE);
getSupportFragmentManager().beginTransaction()
.replace(R.id.loading, new StoryListFragment()).commit();
}
StoryItemsActivity (MagazinePagesActivity and StoryListActivity extend this class; this class extends JSONItemsActivity, which SplashActivity also extends):
package com.dailybruin.bruinframework.channels;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.dailybruin.bruinframework.R;
import com.dailybruin.bruinframework.base.BaseActivity;
import com.dailybruin.bruinframework.base.URLBuilder;
import android.os.Bundle;
public abstract class StoryItemsActivity extends JSONItemsActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public String sourceURL()
{
return URLBuilder.getPostsURL(getString(R.string.slug));
}
public ArrayList<Item> parseJSON(String jsonString) {
// Using pre-downloaded and parsed JSON
return SplashActivity.downloadedItems;
}
}
Check this part of the code. Line number 27. That is null and hence causing NPE.
Caused by: java.lang.NullPointerException
10-16 19:23:12.632: E/AndroidRuntime(828): at com.dailybruin.bruinframework.channels.StoryListActivity.loadItems(StoryListActivity.java:27)
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);