In the app control panel I found an error report that not only I can't reproduce, but also it make no sense to me.
This is the stacktrace:
java.lang.ClassCastException: java.lang.Object[] cannot be cast to ohm.quickdice.entity.RollResult[]
at ohm.quickdice.activity.QuickDiceActivity.setupRollMenu(QuickDiceActivity.java:575)
at ohm.quickdice.activity.QuickDiceActivity.onCreateContextMenu(QuickDiceActivity.java:459)
at android.view.View.createContextMenu(View.java:6229)
at com.android.internal.view.menu.ContextMenuBuilder.show(ContextMenuBuilder.java:81)
at com.android.internal.policy.impl.PhoneWindow$DecorView.showContextMenuForChild(PhoneWindow.java:2292)
at android.view.ViewGroup.showContextMenuForChild(ViewGroup.java:564)
at android.view.ViewGroup.showContextMenuForChild(ViewGroup.java:564)
at android.view.ViewGroup.showContextMenuForChild(ViewGroup.java:564)
at android.view.ViewGroup.showContextMenuForChild(ViewGroup.java:564)
at android.widget.AbsListView.performLongPress(AbsListView.java:2772)
at android.widget.AbsListView$CheckForLongPress.run(AbsListView.java:2717)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4514)
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:790)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
at dalvik.system.NativeStart.main(Native Method)
An this is the code where the exception occour:
ArrayList<RollResult[]> resultList;
RollResult[] lastResult;
...
protected void setupRollMenu(int index, ContextMenu menu) {
RollResult[] rollItem;
RollResult[] nextItem;
RollResult mergedRoll;
if (index < 0) {
rollItem = lastResult;
} else {
rollItem = resultList.get(index);
}
if (index + 1 < resultList.size()) {
nextItem = resultList.get(index + 1); //This is row 575
} else {
nextItem = null;
}
...
I wonder how the instruction "nextItem = resultList.get(int);" can raise this exception since resultList is defined as ArrayList and nextItem is an object of type RollResult[]...
It may depend on how Android serialize and deserialize instance state data to bundles?
Here how the serialization is done:
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putSerializable(KEY_LAST_ROLL, lastResult);
outState.putSerializable(KEY_ROLL_LIST, resultList);
super.onSaveInstanceState(outState);
}
and this is the deserialization:
#SuppressWarnings("unchecked")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
Serializable tmp;
tmp = savedInstanceState.getSerializable(KEY_LAST_ROLL);
if (tmp instanceof RollResult[]) {
lastResult = (RollResult[])tmp;
}
tmp = savedInstanceState.getSerializable(KEY_ROLL_LIST);
if (tmp instanceof ArrayList<?>) {
resultList = (ArrayList<RollResult[]>)tmp;
}
}
if (lastResult == null) {
lastResult = new RollResult[0];
}
if (resultList == null) {
resultList = new ArrayList<RollResult[]>();
}
}
Thanks.
Related
I am trying to make glsurfaceview a part of my layout. It returns an error at a line I am sure about and I don't understand why.
My GLGame class:
public abstract class GLGame extends Activity implements Game, Renderer {
enum GLGameState {
Initialized,
Running,
Paused,
Finished,
Idle
}
GLSurfaceView glView;
GLGraphics glGraphics;
Audio audio;
Input input;
FileIO fileIO;
Screen screen;
GLGameState state = GLGameState.Initialized;
Object stateChanged = new Object();
long startTime = System.nanoTime();
WakeLock wakeLock;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
glView =(GLSurfaceView) this.findViewById (R.id.glSurface);
glView.setRenderer(this); //Failing line
setContentView(R.layout.main);
glGraphics = new GLGraphics(glView);
fileIO = new AndroidFileIO(getAssets());
audio = new AndroidAudio(this);
input = new AndroidInput(this, glView, 1, 1);
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "GLGame");
}
public void onResume() {
super.onResume();
glView.onResume();
wakeLock.acquire();
}
#Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
glGraphics.setGL(gl);
synchronized(stateChanged) {
if(state == GLGameState.Initialized)
screen = getStartScreen();
state = GLGameState.Running;
screen.resume();
startTime = System.nanoTime();
}
}
#Override
public void onSurfaceChanged(GL10 gl, int width, int height) {
}
#Override
public void onDrawFrame(GL10 gl) {
GLGameState state = null;
synchronized(stateChanged) {
state = this.state;
}
if(state == GLGameState.Running) {
float deltaTime = (System.nanoTime()-startTime) / 1000000000.0f;
startTime = System.nanoTime();
screen.update(deltaTime);
screen.present(deltaTime);
}
if(state == GLGameState.Paused) {
screen.pause();
synchronized(stateChanged) {
this.state = GLGameState.Idle;
stateChanged.notifyAll();
}
}
if(state == GLGameState.Finished) {
screen.pause();
screen.dispose();
synchronized(stateChanged) {
this.state = GLGameState.Idle;
stateChanged.notifyAll();
}
}
}
#Override
public void onPause() {
synchronized(stateChanged) {
if(isFinishing())
state = GLGameState.Finished;
else
state = GLGameState.Paused;
while(true) {
try {
stateChanged.wait();
break;
} catch(InterruptedException e) {
}
}
}
wakeLock.release();
glView.onPause();
super.onPause();
}
public GLGraphics getGLGraphics() {
return glGraphics;
}
#Override
public Input getInput() {
return input;
}
#Override
public FileIO getFileIO() {
return fileIO;
}
#Override
public Graphics getGraphics() {
throw new IllegalStateException("We are using OpenGL!");
}
#Override
public Audio getAudio() {
return audio;
}
#Override
public void setScreen(Screen screen) {
if (screen == null)
throw new IllegalArgumentException("Screen must not be null");
this.screen.pause();
this.screen.dispose();
screen.resume();
screen.update(0);
this.screen = screen;
}
#Override
public Screen getCurrentScreen() {
return screen;
}
}
Logcat:
03-25 16:44:51.683 4919-4919/com.badlogic.androidgames.glbasics E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.badlogic.androidgames.glbasics, PID: 4919
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.badlogic.androidgames.glbasics/com.badlogic.androidgames.glbasics.GLGameTest}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.opengl.GLSurfaceView.setRenderer(android.opengl.GLSurfaceView$Renderer)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2329)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
at android.app.ActivityThread.access$900(ActivityThread.java:147)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1296)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5256)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.opengl.GLSurfaceView.setRenderer(android.opengl.GLSurfaceView$Renderer)' on a null object reference
at com.badlogic.androidgames.framework.impl.GLGame.onCreate(GLGame.java:51)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2282)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
at android.app.ActivityThread.access$900(ActivityThread.java:147)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1296)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5256)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
Everything worked fine until I decided I want other things than just glsurfaceview.
I think I am just making a silly mistake, but since the time presses I would be glad if you helped.
Thanks
EDIT: the issue turned out to be that I am unable to findviewbyid from here for some reason. I also tried this:
GLGame.glView = (GLSurfaceView) ((Activity)getApplicationContext()).findViewById (R.id.glSurface);
As it turned out, I am incredibly dumb for writing in in the wrong order. It is supposed to be like this:
setContentView(R.layout.main);
GLGame.glView = (GLSurfaceView) this.findViewById(R.id.glSurface);
glView.setRenderer(this);
I need to add a search bar in my app, but all the tutorials I tried is not working. Because I want this bar to return the values of my ListView imported from Excel (I applied in a way that the Activity shows the names of people). My ListView is imported from Excel, not created in-app code.
That is, when I search for "A" all the names of the ListView with "A" appears when I search "Arn", appear the names containing "Arn" (E.g. Arnold Clinton).
This is the code of TabelaActivity.java:
package com.akzonobel.malote.tabela;
import com.akzonobel.malote.R;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.ListView;
public class TabelaActivity extends Activity {
CSVAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabela);
ListView mList = (ListView)findViewById(R.id.mList);
mAdapter = new CSVAdapter(this, -1);
mList.setAdapter(mAdapter);
}
}
This is the code of CSVAdapter.java:
package com.akzonobel.malote.tabela;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class CSVAdapter extends ArrayAdapter<State>{
Context ctx;
public CSVAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
this.ctx = context;
loadArrayFromFile();
}
#Override
public View getView(final int pos, View convertView, final ViewGroup parent){
TextView mView = (TextView)convertView;
if(null == mView){
mView = new TextView(parent.getContext());
mView.setTextSize(19);
mView.setTextColor(Color.WHITE);
}
mView.setText(getItem(pos).getName());
return mView;
}
private void loadArrayFromFile(){
try {
InputStream is = ctx.getAssets().open("states.csv");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = reader.readLine()) != null) {
State cur = new State();
cur.setName(line);
this.add(cur);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is the code of State.java:
package com.akzonobel.malote.tabela;
public class State {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I tried to apply this search bar:
EditText inputSearch;
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
TabelaActivity.this.mAdapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
The search bar works, can you enter. But when I type the value... it just does not return anything, goes blank. Any help? How to make it work? Or is there another easy way to make a search bar? Can the ActionBar.. the important thing is it works.
Then I tried to apply the getFilter in CSVAdapter, but then when I try to use the bar with this getFilter, it crashes and closes alone.
This is the code I applied getFilter:
private List<State> allModelItemsArray;
private List<State> filteredModelItemsArray;
private Filter filter;
#Override
public Filter getFilter() {
if (filter == null){
filter = new ModelFilter();
}
return filter;
}
private class ModelFilter extends Filter
{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
ArrayList<State> filteredItems = new ArrayList<State>();
for(int i = 0, l = allModelItemsArray.size(); i < l; i++)
{
State m = allModelItemsArray.get(i);
if(m.getName().toLowerCase().contains(constraint))
filteredItems.add(m);
}
result.count = filteredItems.size();
result.values = filteredItems;
}
else
{
synchronized(this)
{
result.values = allModelItemsArray;
result.count = allModelItemsArray.size();
}
}
return result;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredModelItemsArray = (ArrayList<State>)results.values;
notifyDataSetChanged();
clear();
for(int i = 0, l = filteredModelItemsArray.size(); i < l; i++)
add(filteredModelItemsArray.get(i));
notifyDataSetInvalidated();
}
}
And when this is active getFilter, besides closing, it gives the following error in LogCat:
07-13 08:32:52.925: W/Filter(30254): An exception occured during performFiltering()!
07-13 08:32:52.925: W/Filter(30254): java.lang.NullPointerException
07-13 08:32:52.925: W/Filter(30254): at com.akzonobel.malote.tabela.CSVAdapter$ModelFilter.performFiltering(CSVAdapter.java:129)
07-13 08:32:52.925: W/Filter(30254): at android.widget.Filter$RequestHandler.handleMessage(Filter.java:234)
07-13 08:32:52.925: W/Filter(30254): at android.os.Handler.dispatchMessage(Handler.java:99)
07-13 08:32:52.925: W/Filter(30254): at android.os.Looper.loop(Looper.java:137)
07-13 08:32:52.925: W/Filter(30254): at android.os.HandlerThread.run(HandlerThread.java:60)
07-13 08:33:14.856: D/AndroidRuntime(30254): Shutting down VM
07-13 08:33:14.856: W/dalvikvm(30254): threadid=1: thread exiting with uncaught exception (group=0x41101930)
07-13 08:33:14.876: E/AndroidRuntime(30254): FATAL EXCEPTION: main
07-13 08:33:14.876: E/AndroidRuntime(30254): java.lang.NullPointerException
07-13 08:33:14.876: E/AndroidRuntime(30254): at com.akzonobel.malote.tabela.CSVAdapter$ModelFilter.publishResults(CSVAdapter.java:156)
07-13 08:33:14.876: E/AndroidRuntime(30254): at android.widget.Filter$ResultsHandler.handleMessage(Filter.java:282)
07-13 08:33:14.876: E/AndroidRuntime(30254): at android.os.Handler.dispatchMessage(Handler.java:99)
07-13 08:33:14.876: E/AndroidRuntime(30254): at android.os.Looper.loop(Looper.java:137)
07-13 08:33:14.876: E/AndroidRuntime(30254): at android.app.ActivityThread.main(ActivityThread.java:5283)
07-13 08:33:14.876: E/AndroidRuntime(30254): at java.lang.reflect.Method.invokeNative(Native Method)
07-13 08:33:14.876: E/AndroidRuntime(30254): at java.lang.reflect.Method.invoke(Method.java:511)
07-13 08:33:14.876: E/AndroidRuntime(30254): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
07-13 08:33:14.876: E/AndroidRuntime(30254): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
07-13 08:33:14.876: E/AndroidRuntime(30254): at dalvik.system.NativeStart.main(Native Method)
Add a constructor to the State class:
public State(String name) {
this.name = name;
}
Don't use the global allModelItemsArray and filteredItemsArray, get rid of them.
Then change your performFiltering function like this:
#Override
protected FilterResults performFiltering(CharSequence constraint) {
constraint = constraint.toString().toLowerCase();
FilterResults result = new FilterResults();
if(constraint != null && constraint.toString().length() > 0)
{
ArrayList<State> filteredItems = new ArrayList<State>();
for(int i = 0, l = getCount(); i < l; i++)
{
State m = getItem(i);
if(m.getName().toLowerCase().contains(constraint))
filteredItems.add(m);
}
result.count = filteredItems.size();
result.values = filteredItems;
}
else
{
ArrayList<State> allItems = new ArrayList<State>();
for(int i = 0, l = getCount(); i < l; i++)
{
State m = getItem(i);
allItems.add(m);
}
synchronized(this)
{
result.values = allItems;
result.count = allItems.size();
}
}
return result;
}
This will work much better and is proper way to fix this.
I try to get current location and user activity, following the guide from
http://j.mp/io13-location the "checkpoint_final"
but i got those error when i run the program.
my logCat:
02-21 18:12:38.439: E/AndroidRuntime(3798): FATAL EXCEPTION: main
02-21 18:12:38.439: E/AndroidRuntime(3798): Process: com.android.google.codelab.location, PID: 3798
02-21 18:12:38.439: E/AndroidRuntime(3798): java.lang.RuntimeException: Unable to resume activity {com.android.google.codelab.location/com.android.google.codelab.location.LocationActivity}: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2788)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2817)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.access$800(ActivityThread.java:135)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.os.Handler.dispatchMessage(Handler.java:102)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.os.Looper.loop(Looper.java:136)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.main(ActivityThread.java:5017)
02-21 18:12:38.439: E/AndroidRuntime(3798): at java.lang.reflect.Method.invokeNative(Native Method)
02-21 18:12:38.439: E/AndroidRuntime(3798): at java.lang.reflect.Method.invoke(Method.java:515)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-21 18:12:38.439: E/AndroidRuntime(3798): at dalvik.system.NativeStart.main(Native Method)
02-21 18:12:38.439: E/AndroidRuntime(3798): Caused by: java.lang.IllegalStateException: Not connected. Call connect() and wait for onConnected() to be called.
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.dk.bB(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.fm.a(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.fm$c.bB(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.fl.requestLocationUpdates(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.fm.requestLocationUpdates(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.internal.fm.requestLocationUpdates(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.google.android.gms.location.LocationClient.requestLocationUpdates(Unknown Source)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.android.google.codelab.location.LocationActivity.restartLocationClient(LocationActivity.java:248)
02-21 18:12:38.439: E/AndroidRuntime(3798): at com.android.google.codelab.location.LocationActivity.onResume(LocationActivity.java:197)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1192)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.Activity.performResume(Activity.java:5310)
02-21 18:12:38.439: E/AndroidRuntime(3798): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2778)
02-21 18:12:38.439: E/AndroidRuntime(3798): ... 12 more
my Code
public class LocationActivity extends FragmentActivity {
public static String TAG = "LocationActivity";
public static boolean isAppForeground = false;
private static final int ERROR_DIALOG_ON_CREATE_REQUEST_CODE = 4055;
private static final int ERROR_DIALOG_ON_RESUME_REQUEST_CODE = 4056;
// Shared variables
private GoogleMap mMap;
private Dialog errorDialog;
// Location Request variables
private LocationClient mLocationClient;
private TextView mLocationStatus;
private LocationCallback mLocationCallback = new LocationCallback();
private Location mLastLocation;
private static final int LOCATION_UPDATES_INTERVAL = 10000; // Setting 10 sec interval for location updates
// Activity Recognition variables
private ActivityRecognitionClient mActivityRecognitionClient;
private ActivityRecognitionCallback mActivityRecognitionCallback = new ActivityRecognitionCallback();
public static final String ACTION_ACTIVITY_RECOGNITION =
"com.android.google.codelab.location.LocationActivity.ACTIVITY_RECOGNITION";
private static final int ACTIVITY_UPDATES_INTERVAL = 4000;
private PendingIntent mActivityRecognitionPendingIntent;
private Switch mSwitch;
private ActivityRecognitionIntentReceiver mActivityRecognitionIntentReceiver;
// Geo Fencing variables
private GeoFenceCallback mGeoFenceCallback = new GeoFenceCallback();
private int id = 0;
private static final float GEOFENCE_RADIUS = 100;
private HashMap<String, Circle> mGeoFences;
private HashMap<String, Circle> mTriggeringFences;
public static final String ACTION_GEOFENCE =
"com.android.google.codelab.location.LocationActivity.GEOFENCE";
private TextView mGeoFenceStatus;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkGooglePlayServiceAvailability(ERROR_DIALOG_ON_CREATE_REQUEST_CODE);
}
private void init() {
// Initialize map
if (mMap == null) {
FragmentManager myFragmentManager = getSupportFragmentManager();
SupportMapFragment myMapFragment =
(SupportMapFragment) myFragmentManager.findFragmentById(R.id.map);
mMap = myMapFragment.getMap();
}
// Initialize Location Client
mLocationStatus = (TextView) findViewById(R.id.location_status);
if (mLocationClient == null) {
mLocationClient = new LocationClient(this, mLocationCallback, mLocationCallback);
Log.v(LocationActivity.TAG, "Location Client connect");
if (!(mLocationClient.isConnected() || mLocationClient.isConnecting())) {
mLocationClient.connect();
}
}
// Initialize Action Recognition
if (mActivityRecognitionClient == null) {
mActivityRecognitionClient =
new ActivityRecognitionClient(this,
mActivityRecognitionCallback, mActivityRecognitionCallback);
}
mSwitch = (Switch) findViewById(R.id.swtich);
mSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
startActivityDetection(buttonView);
} else {
stopActivityDetection(buttonView);
}
}
});
if (mActivityRecognitionIntentReceiver == null) {
mActivityRecognitionIntentReceiver = new ActivityRecognitionIntentReceiver();
registerReceiver(mActivityRecognitionIntentReceiver,
new IntentFilter(LocationActivity.ACTION_ACTIVITY_RECOGNITION));
}
// Initialize Geo Fencing
mGeoFenceStatus = (TextView) findViewById(R.id.geo_fence_status);
if (mGeoFences == null) {
mGeoFences = new HashMap<String, Circle>();
}
if (mTriggeringFences == null) {
mTriggeringFences = new HashMap<String, Circle>();
}
// Setup map to allow adding Geo Fences
mMap.getUiSettings().setAllGesturesEnabled(true);
mMap.setOnMapLongClickListener(mGeoFenceCallback);
}
#Override
public void onPause() {
super.onPause();
// Indicate the application is in background
isAppForeground = false;
if (mLocationClient.isConnected()) {
mLocationClient.removeLocationUpdates(mLocationCallback);
mLocationClient.disconnect();
}
}
#Override
public void onResume() {
super.onResume();
// Indicate the application is in foreground
isAppForeground = true;
checkGooglePlayServiceAvailability(ERROR_DIALOG_ON_RESUME_REQUEST_CODE);
restartLocationClient();
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mActivityRecognitionIntentReceiver);
mActivityRecognitionIntentReceiver = null;
}
private void checkGooglePlayServiceAvailability(int requestCode) {
// Query for the status of Google Play services on the device
int statusCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (statusCode == ConnectionResult.SUCCESS) {
init();
} else {
if (GooglePlayServicesUtil.isUserRecoverableError(statusCode)) {
errorDialog = GooglePlayServicesUtil.getErrorDialog(statusCode,
this, requestCode);
errorDialog.show();
} else {
// Handle unrecoverable error
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
switch (requestCode) {
case ERROR_DIALOG_ON_CREATE_REQUEST_CODE:
init();
break;
case ERROR_DIALOG_ON_RESUME_REQUEST_CODE:
restartLocationClient();
break;
}
}
}
private void restartLocationClient() {
if (!(mLocationClient.isConnected() || mLocationClient.isConnecting())) {
mLocationClient.connect(); // Somehow it becomes connected here
return;
}
LocationRequest request = LocationRequest.create();
request.setInterval(LOCATION_UPDATES_INTERVAL);
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationClient.requestLocationUpdates(request, mLocationCallback);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuItem menuItem = menu.add(R.string.clear_map);
menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
menuItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
clearMap();
return true;
}
});
return true;
}
public void clearMap() {
mMap.clear();
mLastLocation = null;
mGeoFenceCallback.removeGeoFences();
}
private class LocationCallback implements ConnectionCallbacks, OnConnectionFailedListener,
LocationListener {
#Override
public void onConnected(Bundle connectionHint) {
Log.v(LocationActivity.TAG, "Location Client connected");
// Display last location
Location location = mLocationClient.getLastLocation();
if (location != null) {
handleLocation(location);
}
// Request for location updates
LocationRequest request = LocationRequest.create();
request.setInterval(LOCATION_UPDATES_INTERVAL);
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationClient.requestLocationUpdates(request, mLocationCallback);
}
#Override
public void onDisconnected() {
Log.v(LocationActivity.TAG, "Location Client disconnected by the system");
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.v(LocationActivity.TAG, "Location Client connection failed");
}
#Override
public void onLocationChanged(Location location) {
if (location == null) {
Log.v(LocationActivity.TAG, "onLocationChanged: location == null");
return;
}
// Add a marker iff location has changed.
if (mLastLocation != null &&
mLastLocation.getLatitude() == location.getLatitude() &&
mLastLocation.getLongitude() == location.getLongitude()) {
return;
}
handleLocation(location);
}
private void handleLocation(Location location) {
// Update the mLocationStatus with the lat/lng of the location
Log.v(LocationActivity.TAG, "LocationChanged == #" +
location.getLatitude() + "," + location.getLongitude());
mLocationStatus.setText("Location changed #" + location.getLatitude() + "," +
location.getLongitude());
// Add a marker of that location to the map
LatLng latlongzoom = new LatLng(location.getLatitude(),
location.getLongitude());
String snippet = location.getLatitude() + "," + location.getLongitude();
Marker marker = mMap.addMarker(
new MarkerOptions().position(latlongzoom));
marker.setSnippet(snippet);
marker.setTitle(snippet);
// Center the map to the first marker
if (mLastLocation == null) {
mMap.moveCamera(CameraUpdateFactory.
newCameraPosition(CameraPosition.fromLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()),
(float) 16.0)));
}
mLastLocation = location;
}
};
public void startActivityDetection(View v) {
if (!mActivityRecognitionClient.isConnected()) {
mActivityRecognitionClient.connect();
}
}
public void stopActivityDetection(View v) {
if (mActivityRecognitionClient.isConnected()) {
mActivityRecognitionClient.removeActivityUpdates(mActivityRecognitionPendingIntent);
mActivityRecognitionClient.disconnect();
}
}
private class ActivityRecognitionCallback implements ConnectionCallbacks, OnConnectionFailedListener {
#Override
public void onConnected(Bundle connectionHint) {
Log.v(LocationActivity.TAG, "Activity Recognition Client connected");
// Request activity updates
Intent intent = new Intent(LocationActivity.this,
ActivityRecognitionIntentService.class);
intent.setAction(LocationActivity.ACTION_ACTIVITY_RECOGNITION);
mActivityRecognitionPendingIntent = PendingIntent.getService(LocationActivity.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
mActivityRecognitionClient.requestActivityUpdates(ACTIVITY_UPDATES_INTERVAL,
mActivityRecognitionPendingIntent);
}
#Override
public void onDisconnected() {
Log.v(LocationActivity.TAG, "Activity Recognition Client disconnected by the system");
}
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.v(LocationActivity.TAG,
"Activity Recognition Client connection failed " + result.getErrorCode());
}
};
private class GeoFenceCallback implements OnMapLongClickListener,
OnAddGeofencesResultListener, OnRemoveGeofencesResultListener {
#Override
public void onMapLongClick(LatLng point) {
Log.v(LocationActivity.TAG,
"onMapLongClick == " + point.latitude + "," + point.longitude);
CircleOptions circleOptions = new CircleOptions();
circleOptions.center(point).radius(GEOFENCE_RADIUS).strokeColor(
android.graphics.Color.BLUE).strokeWidth(2);
Circle circle = mMap.addCircle(circleOptions);
String key = Integer.toString(id);
id++;
mGeoFences.put(key, circle);
addGeoFences();
}
// Creates Geofence objects from all circles on the map and calls addGeofences API.
private void addGeoFences() {
List<Geofence> list = new ArrayList<Geofence>();
for (Map.Entry<String, Circle> entry : mGeoFences.entrySet()) {
Circle circle = entry.getValue();
Log.v(LocationActivity.TAG, "points == " +
circle.getCenter().latitude + "," +
circle.getCenter().longitude);
Geofence geofence = new Geofence.Builder()
.setRequestId(entry.getKey())
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER |
Geofence.GEOFENCE_TRANSITION_EXIT)
.setCircularRegion(circle.getCenter().latitude,
circle.getCenter().longitude,
(float) circle.getRadius())
.setExpirationDuration(Geofence.NEVER_EXPIRE).build();
list.add(geofence);
}
if (list.isEmpty()) {
return;
}
// Clear off all the currently triggering geo_fences before new fences
// are added.
for (Circle triggeringGeoFence : mTriggeringFences.values()) {
triggeringGeoFence.remove();
}
mTriggeringFences.clear();
Log.v(LocationActivity.TAG, "addingGeoFences size = " + list.size());
mLocationClient.addGeofences(list, getPendingIntent(), this);
}
private PendingIntent getPendingIntent() {
Intent intent = new Intent(ACTION_GEOFENCE);
intent.setComponent(new ComponentName(LocationActivity.this,
GeoFenceIntentReceiver.class));
return PendingIntent.getBroadcast(LocationActivity.this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
private void removeGeoFences() {
List<String> requestIdsForRemoval = new ArrayList<String>();
if (mGeoFences.isEmpty()) return;
for (Map.Entry<String, Circle> entry : mGeoFences.entrySet()) {
String requestId = entry.getKey();
Circle circle = entry.getValue();
if (circle != null) {
circle.remove();
id --;
Log.v(LocationActivity.TAG, "RemoveGeoFence requestId == " + requestId);
Circle triggeringCircle = mTriggeringFences.get(requestId);
if (triggeringCircle != null) {
triggeringCircle.remove();
}
requestIdsForRemoval.add(requestId);
}
}
mGeoFences.clear();
mTriggeringFences.clear();
mLocationClient.removeGeofences(requestIdsForRemoval, this);
}
#Override
public void onAddGeofencesResult(int statusCode,
String[] geofenceRequestIds) {
StringBuilder builder = new StringBuilder();
for (int i = 0 ; i < geofenceRequestIds.length - 1; ++i) {
builder.append(geofenceRequestIds[i]);
builder.append(",");
}
builder.append(geofenceRequestIds[geofenceRequestIds.length - 1]);
Log.v(LocationActivity.TAG, "Added Geofences == "
+ statusCodeToString(statusCode) + " " + builder.toString());
mGeoFenceStatus.setText("Added Geofences "
+ statusCodeToString(statusCode) + " " + builder.toString());
}
private String statusCodeToString(int statusCode) {
switch(statusCode) {
case LocationStatusCodes.SUCCESS :
return "SUCCESS";
case LocationStatusCodes.GEOFENCE_NOT_AVAILABLE :
return "GEOFENCE_NOT_AVAILABLE";
case LocationStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES :
return "GEOFENCE_TOO_MANY_GEOFENCES";
case LocationStatusCodes.GEOFENCE_TOO_MANY_PENDING_INTENTS :
return "GEOFENCE_TOO_MANY_PENDING_INTENTS";
case LocationStatusCodes.ERROR :
return "ERROR";
}
return "UNKNOWN";
}
#Override
public void onRemoveGeofencesByPendingIntentResult(int statusCode, PendingIntent pendingIntent) {
// Do nothing
}
#Override
public void onRemoveGeofencesByRequestIdsResult(int statusCode,
String[] geofenceRequestIds) {
StringBuilder builder = new StringBuilder();
for (int i = 0 ; i < geofenceRequestIds.length - 1; ++i) {
builder.append(geofenceRequestIds[i]);
builder.append(",");
}
builder.append(geofenceRequestIds[geofenceRequestIds.length - 1]);
Log.v(LocationActivity.TAG, "Removed Geofence " +
statusCodeToString(statusCode) + " " + builder.toString());
mGeoFenceStatus.setText("Removed Geofences request_ids = " +
builder.toString() + " " + statusCodeToString(statusCode));
}
};
// Triggered when startAcitivity method is called in GeoFenceIntentReceiver.
// Updates UI as geofences are entered/exited.
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// getIntent() should always return the most recent
setIntent(intent);
boolean receiverStarted =
intent.getBooleanExtra("RECEIVER_STARTED", false);
if (!receiverStarted) {
return;
}
Bundle bundle = intent.getParcelableExtra("geo_fences");
ArrayList<String> requestIds =
bundle.getStringArrayList("request_ids");
if (requestIds == null) {
Log.v(LocationActivity.TAG, "request_ids == null");
return;
}
int transition = intent.getIntExtra("transition", -2);
for (String requestId : requestIds) {
Log.v(LocationActivity.TAG, "Triggering Geo Fence requestId "
+ requestId);
if (transition == Geofence.GEOFENCE_TRANSITION_ENTER) {
Circle circle = mGeoFences.get(requestId);
if (circle == null) {
continue;
}
Log.v(LocationActivity.TAG, "triggering_geo_fences enter == "
+ requestId);
// Add a superimposed red circle when a geofence is entered and
// put the corresponding object in triggering_fences.
CircleOptions circleOptions = new CircleOptions();
circleOptions.center(circle.getCenter())
.radius(circle.getRadius())
.fillColor(Color.argb(100,100, 0, 0));
Circle newCircle = mMap.addCircle(circleOptions);
mTriggeringFences.put(requestId, newCircle);
} else if (transition == Geofence.GEOFENCE_TRANSITION_EXIT) {
Log.v(LocationActivity.TAG, "triggering_geo_fences exit == "
+ requestId);
Circle circle = mTriggeringFences.get(requestId);
if (circle == null) {
continue;
}
// Remove the superimposed red circle from the map and the
// corresponding Circle object from triggering_fences hash_map.
circle.remove();
mTriggeringFences.remove(requestId);
}
}
return;
}
}
2nd class
public class ActivityRecognitionIntentService extends IntentService {
public ActivityRecognitionIntentService() {
super("ActivityRecognitionIntentService");
}
public ActivityRecognitionIntentService(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent.getAction() != LocationActivity.ACTION_ACTIVITY_RECOGNITION) {
return;
}
if (ActivityRecognitionResult.hasResult(intent)) {
ActivityRecognitionResult result = ActivityRecognitionResult
.extractResult(intent);
DetectedActivity detectedActivity = result
.getMostProbableActivity();
int activityType = detectedActivity.getType();
Log.v(LocationActivity.TAG, "activity_type == " + activityType);
// Put the activity_type as an intent extra and send a broadcast.
Intent send_intent = new Intent(
LocationActivity.ACTION_ACTIVITY_RECOGNITION);
send_intent.putExtra("activity_type", activityType);
sendBroadcast(send_intent);
}
}
}
edited add the main part of the code
Please Modify your restartLocationClient() Method like this:
private void restartLocationClient() {
if (mLocationClient == null) {
mLocationClient = new LocationClient(this, mLocationCallback, mLocationCallback);
Log.v(LocationActivity.TAG, "Location Client connect");
if (!(mLocationClient.isConnected() || mLocationClient.isConnecting()))
{
mLocationClient.connect(); // Somehow it becomes connected here
return;
}
}
LocationRequest request = LocationRequest.create();
request.setInterval(LOCATION_UPDATES_INTERVAL);
request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationClient.requestLocationUpdates(request, mLocationCallback);
}
It seems that your mLocationClient is null in this Method.
I hope this helps.
I know it's pretty late for this answer.
But for future reference, I'll post it anyways.
Basically, we have to understand the onConnect() method better. I find the explanation in this thread to be useful.
From there the workaround for this issue is pretty much straightforward.
Solution: restartLocationClient() is only called when mLocationClient.isConnected() returns true.
So, in your onResume method should look like the following:
if (mLocationClient.isConnected()) {
restartLocationClient();
}
Now it will work.
Im having a hard time to figure it out why my image are showing duplicate in my costume grid (staggeredgridview)
the progam using lazy method to fetch image from webservice and insert into db , if user access the program without internet or accesss the old image data will be fetch from local db instead.
here is my main class :
private int index;
private Mysecondworker msw;
private main activity;
private String value;
private int filter = 0;
private boolean isLoading = false;
private int Sort = 0;
private StaggeredGridView mystaggerdgridview ;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mystaggerdgridview = (StaggeredGridView) findViewById(R.id.grid);
mystaggerdgridview.setColumnCount(2);
activity = this;
loadingisactive(true);
msw = new Mysecondworker(activity, value, String.valueOf(index++), 0,0);
msw.execute();
mystaggerdgridview .setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(ViewGroup view, int scrollState) {
public void onScroll(ViewGroup view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
boolean needtofetchMore = firstVisibleItem + visibleItemCount >= totalItemCount ;
if (needtofetchMore && !loadingisactive){
loadingisactive= true;
hw = new Mysecondworker(activity, value, String.valueOf(index++), filter,Sort);
hw.execute();
}
}
});
}
private Thread performOnBackgroundThread(final Runnable runnable) {
final Thread t = new Thread() {
#Override
public void run() {
try {
runnable.run();
} finally {
}
}
};
t.start();
return t;
}
public void setloadingisactive(boolean flag){
loadingisactive= flag;
}
and my Mysecondworker class :
public class Mysecondworker
extends
AsyncTask<String, String, AsyncTaskResult<ArrayList<HashMap<String, String>>>> {
private main targetCtx;
private String Mysecondworker_key;
myAdapter myadapter;
private LinearLayout Mysecondworker_progress;
private String Mysecondworker_index , Mysecondworker_sort;
private int Mysecondworker_filter = 0;
private LinearLayout Mysecondworker_pagination;
private ImageView Mysecondworker_imgPagination;
private AnimationDrawable Mysecondworker_frameAnimation;
private String Mysecondworker_lastID = "0";
private StaggeredGridView mystaggerdgridview ;
public Mysecondworker(main mycontext, String mykey, String myindex, int myfilter,int mysort) {
this.targetCtx = mycontext;
Mysecondworker_key = mykey;
mystaggerdgridview = (StaggeredGridView) targetCtx.findViewById(id.grid);
Mysecondworker_index = myindex;
Mysecondworker_filter = myfilter;
Mysecondworker_sort = String.valueOf(mysort);
Mysecondworker_pagination = (LinearLayout) targetCtx.findViewById(id.pagination_load);
Mysecondworker_imgPagination = (ImageView) targetCtx
.findViewById(id.loadingpaginganimation);
#Override
protected void onPreExecute() {
progress = (LinearLayout) targetCtx.findViewById(R.id.progress);
if (Integer.parseInt(index) == 0)
Mysecondworker_progress.setVisibility(View.VISIBLE);
Mysecondworker_pagination.setVisibility(View.VISIBLE);
Mysecondworker_imgPagination.setBackgroundResource(R.anim.loadanimation);
Mysecondworker_frameAnimation = (AnimationDrawable) Mysecondworker_imgPagination.getBackground();
Mysecondworker_frameAnimation.start();
//finding the last id of images
myAdapter mAd = (myAdapter) mystaggerdgridview.getAdapter();
if (mAd != null && mAd.getCount() > 0) {
lastID = mAd.getData().get(mAd.getCount() - 1).get("id");
}else
lastID = "0";
}
#Override
protected AsyncTaskResult<ArrayList<HashMap<String, String>>> doInBackground(
String... param) {
try {
String xml = [[[getting image from web service with unique id for each one]]]
SaxXmlParser mygalleryparser = new SaxXmlParser(xml, "imagegallery");
mygalleryparser.runParser();
if (Integer.parseInt(Mysecondworker_index) == 0 && Integer.parseInt(Mysecondworker_key) > 0) {
table_imagegallery obj_imagegallery = new table_imagegallery();
obj_imagegallery.subjectId = Integer.parseInt(Mysecondworker_key);
obj_imagegallery.DeleteBySubjectId();
}
for (HashMap<String, String> hashMap : mygalleryparser.getParsedData()) {
table_imagegallery imagegallery = new table_imagegallery();
imagegallery.id = Integer.parseInt(hashMap.get("id"));
if (Integer.parseInt(key) < 1) {
imagegallery.Delete();
}
imagegallery.imgageurl = hashMap.get("imageurlfromxml");
imagegallery.Insert();
}
AsyncTaskResult<ArrayList<HashMap<String, String>>> myresult = new AsyncTaskResult<ArrayList<HashMap<String, String>>>(
mygalleryparser.getParsedData());
return myresult;
} catch (Exception e) {
ArrayList<HashMap<String, String>> myresult = new ArrayList<HashMap<String, String>>();
table_imagegallery forofflinefetch = new table_imagegallery();
List<table_imagegallery> Off_imagegallery = new ArrayList<table_imagegallery>();
switch (Integer.parseInt(Mysecondworker_key)) {
case -1:
if (Integer.parseInt(Mysecondworker_index) == 0)
Off_imagegallery = forofflinefetch.GetAllImages();
break;
}
for (table_imagegallery imagegallery : Off_imagegallery) {
HashMap<String, String> mapforimage = new HashMap<String, String>();
mapforimage.put("id", String.valueOf(imagegallery.id));
mapforimage.put("thumb_url1", imagegallery.imgageurl);
myresult.add(mapforimage);
}
AsyncTaskResult<ArrayList<HashMap<String, String>>> myresultReturn = new AsyncTaskResult<ArrayList<HashMap<String, String>>>(
myresult , true);
return myresultReturn;
}
}
#Override
protected void onPostExecute(
AsyncTaskResult<ArrayList<HashMap<String, String>>> myresult) {
Mysecondworker_progress.setVisibility(View.GONE);
Mysecondworker_frameAnimation.stop();
Mysecondworker_pagination.setVisibility(View.GONE);
if (myresult.getError() != null) {
//[[[errorr apear here]]]];
} else {
myAdapter mAd = (myAdapter) mystaggerdgridview.getAdapter();
ArrayList<HashMap<String, String>> outputResult = new ArrayList<HashMap<String, String>>();
if (mAd != null && mAd.getCount() > 0) {
outputResult = mAd.getData();
}
outputResult.addAll(myresult.getResult());
if (mAd == null) {
myadapter = new myAdapter(targetCtx, outputResult);
mystaggerdgridview.setAdapter(myadapter);
} else {
mAd.notifyDataSetChanged();
}
if (!myresult.checkforofline())
targetCtx.setloadingisactive(false);
}
}
}
and here is my async class :
public class AsyncTaskResult<T> {
private T myresult = null;
private Exception error = null;
private boolean _checkforofline = false;
public T getResult() {
return myresult;
}
public Exception getError() {
return error;
}
public AsyncTaskResult(T myresult) {
super();
this.myresult = myresult;
}
public AsyncTaskResult(T myresult,boolean isOffline) {
super();
this.myresult = myresult;
_checkforofline = checkforofline;
}
public AsyncTaskResult() {
super();
}
public AsyncTaskResult(Exception error) {
super();
this.error = error;
}
public boolean checkforofline() {
return _checkforofline;
}
and madapter class :
public myAdapter(Activity act, ArrayList<HashMap<String, String>> listhast) {
myactivity = act;
mydata=listhast;
myinflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
myimageLoader=new ImageLoader(activity.getApplicationContext(),true);
}
private Thread performOnBackgroundThread(final Runnable runnable) {
final Thread t = new Thread() {
#Override
public void run() {
try {
runnable.run();
} finally {
}
}
};
t.start();
return t;
}
public int getCount() {
return mydata.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public ArrayList<HashMap<String, String>> getData(){
return mydata;
}
public View getView(final int position, View convertView, ViewGroup parent) {
try {
final myviewholder viewHolder;
final HashMap<String, String> my_data_base_on_position = mydata.get(position);
if (convertView == null) {
if(Integer.parseInt(my_data_base_on_position.get("id")) % 2 == 1){
convertView = mInflater.inflate(R.layout.layoutright, parent, false);
}else{
convertView = mInflater.inflate(R.layout.layoutleft, parent, false);
}
viewHolder = new myviewholder();
viewHolder.tv0 = (TextView) convertView.findViewById(R.id.textid);
viewHolder.imageurl = (ImageView) convertView.findViewById(R.id.image);
convertView.setTag(viewHolder);
}else{
viewHolder = (myviewholder) convertView.getTag();
}
LayoutParams lp;
if(data.size() > 0 ){
viewHolder.tv0.setText(my_data_base_on_position.get("id"));
viewHolder.tv0.setTag(my_data_base_on_position.get("id"));
classtoloadimagefromurl.DisplayImage(my_data_base_on_position.get("imageurl"), viewHolder.imageurl);
lp = new LayoutParams(convertView.getLayoutParams());
lp.span = 1;
convertView.setLayoutParams(lp);
return convertView;
}else{
convertView = mInflater.inflate(R.layout.noimage, parent, false);
lp = new LayoutParams(convertView.getLayoutParams());
lp.span = 1;
convertView.setLayoutParams(lp);
return convertView;
}
}
intresting if i use listview instead of staggeredgrid in my madapter class everything goes fine but if i choose to show item in uneven ui , dupplicate value apears when it try to fetch !
this is the error :
01-09 11:51:52.656: E/Database(29557): Error inserting imagegallery
01-09 11:51:52.656: E/Database(29557): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
01-09 11:51:52.656: E/Database(29557): at android.database.sqlite.SQLiteStatement.native_execute(Native Method)
01-09 11:51:52.656: E/Database(29557): at android.database.sqlite.SQLiteStatement.execute(SQLiteStatement.java:61)
01-09 11:51:52.656: E/Database(29557): at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1584)
01-09 11:51:52.656: E/Database(29557): at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1428)
01-09 11:51:52.656: E/Database(29557): at com.imagegallery.Tabel_for_images.Insert(Tabel_for_images.java:109)
01-09 11:51:52.656: E/Database(29557): at com.imagegallery.Mysecondworker.doInBackground(Mysecondworker.java:141)
01-09 11:51:52.656: E/Database(29557): at com.imagegallery.Mysecondworker.doInBackground(Mysecondworker.java:1)
01-09 11:51:52.656: E/Database(29557): at android.os.AsyncTask$2.call(AsyncTask.java:185)
01-09 11:51:52.656: E/Database(29557): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
01-09 11:51:52.656: E/Database(29557): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
01-09 11:51:52.656: E/Database(29557): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
01-09 11:51:52.656: E/Database(29557): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
01-09 11:51:52.656: E/Database(29557): at java.lang.Thread.run(Thread.java:1019)
I copied some Code and it works, but when I try to make some changes it throws an exception, but I don't know why, because I don't understand all of the code, perhaps someone can help me:
MainActivity.java:
public class MainActivity extends ListActivity {
private File currentDir;
private FileArrayAdapter adapter;
private String SearchString = "test";
List<Option>dir = new ArrayList<Option>();
List<Option>fls = new ArrayList<Option>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
currentDir = new File("/sdcard/Test");
fill(currentDir);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Log.d("TEST", adapter.getItem(position).getPath());//aktuellen Pfad ins Syslog schreiben
Option o = adapter.getItem(position);
onFileClick(o);
}
private void onFileClick(Option o)
{
Log.d("TEST", o.getPath());//aktuellen Pfad ins Syslog schreiben
File file = new File(o.getPath());
Intent opdf = new Intent(Intent.ACTION_VIEW);
opdf.setDataAndType(Uri.fromFile(file), "application/pdf");
opdf.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(opdf);
}
public static String removeExtension(String s) {
String separator = System.getProperty("file.separator");
String filename;
// Remove the path upto the filename.
int lastSeparatorIndex = s.lastIndexOf(separator);
if (lastSeparatorIndex == -1) {
filename = s;
} else {
filename = s.substring(lastSeparatorIndex + 1);
}
// Remove the extension.
int extensionIndex = filename.lastIndexOf(".");
if (extensionIndex == -1)
return filename;
return filename.substring(0, extensionIndex);
}
private void fill(File f)
{
File[]dirs = f.listFiles();
try{
for(File ff: dirs)
{
if(ff.isDirectory()){
File r = new File (ff.getPath());
Log.d("TEST", ff.getPath());//aktuellen Pfad ins Syslog schreiben
fill2(r);
}
else
{
}
}
}catch(Exception e)
{
}
Collections.sort(dir);
Collections.sort(fls);
dir.addAll(fls);
adapter = new FileArrayAdapter(MainActivity.this,R.layout.activity_main,dir);
this.setListAdapter(adapter);
}
private void fill2(File f)
{
File[]dirs = f.listFiles();
try{
for(File ff: dirs)
{
if(ff.isDirectory()){
fill2(ff);
}
else{
String Name = (ff.getName().toLowerCase(Locale.GERMAN));
if (Name.contains(SearchString.toLowerCase(Locale.GERMAN))){
fls.add(new Option(removeExtension(ff.getName()),"",null));
}
}
}
}catch(Exception e)
{
}
}
}
FileArrayAdapter.java:
public class FileArrayAdapter extends ArrayAdapter<Option>{
private Context c;
private int id;
private List<Option>items;
public FileArrayAdapter(Context context, int textViewResourceId,
List<Option> objects) {
super(context, textViewResourceId, objects);
c = context;
id = textViewResourceId;
items = objects;
}
public Option getItem(int i)
{
return items.get(i);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(id, null);
}
final Option o = items.get(position);
if (o != null) {
TextView t1 = (TextView) v.findViewById(R.id.TextView01);
TextView t2 = (TextView) v.findViewById(R.id.TextView02);
if(t1!=null)
t1.setText(o.getName());
if(t2!=null)
t2.setText(o.getData());
//int drawableID = R.drawable.file_icon;
//t1.setCompoundDrawablesWithIntrinsicBounds(drawableID, 0,
// 0, 0);
t1.setEllipsize(null);
t1.setTextSize(54);
t1.setBackgroundColor(Color.LTGRAY);
t2.setBackgroundColor(Color.LTGRAY);
}
return v;
}
}
Option.java:
public class Option implements Comparable<Option>{
private String name;
private String data;
private String path;
public Option(String n,String d,String p)
{
name = n;
data = d;
path = p;
}
public String getName()
{
return name;
}
public String getData()
{
return data;
}
public String getPath()
{
return path;
}
#Override
public int compareTo(Option o) {
if(this.name != null)
return this.name.toLowerCase().compareTo(o.getName().toLowerCase());
else
throw new IllegalArgumentException();
}
}
Logcat:
E/AndroidRuntime(30173): FATAL EXCEPTION: main
E/AndroidRuntime(30173): java.lang.NullPointerException
E/AndroidRuntime(30173): at java.io.File.fixSlashes(File.java:185)
E/AndroidRuntime(30173): at java.io.File.<init>(File.java:134)
E/AndroidRuntime(30173): at com.example.test.MainActivity.onFileClick(MainActivity.java:47)
E/AndroidRuntime(30173): at com.example.test.MainActivity.onListItemClick(MainActivity.java:41)
E/AndroidRuntime(30173): at android.app.ListActivity$2.onItemClick(ListActivity.java:319)
E/AndroidRuntime(30173): at android.widget.AdapterView.performItemClick(AdapterView.java:297)
E/AndroidRuntime(30173): at android.widget.AbsListView.performItemClick(AbsListView.java:1100)
E/AndroidRuntime(30173): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2754)
E/AndroidRuntime(30173): at android.widget.AbsListView$1.run(AbsListView.java:3428)
E/AndroidRuntime(30173): at android.os.Handler.handleCallback(Handler.java:725)
E/AndroidRuntime(30173): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(30173): at android.os.Looper.loop(Looper.java:152)
E/AndroidRuntime(30173): at android.app.ActivityThread.main(ActivityThread.java:5132)
E/AndroidRuntime(30173): at java.lang.reflect.Method.invokeNative(NativeMethod)
E/AndroidRuntime(30173): at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime(30173): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
E/AndroidRuntime(30173): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
E/AndroidRuntime(30173): at dalvik.system.NativeStart.main(Native Method)
W/ActivityManager( 2112): Force finishing activity com.example.test/.MainActivity
In the fill2 method of MainActivity, you're creating an Option object with a null path :
fls.add(new Option(removeExtension(ff.getName()),"",null));
Then you're calling :
File file = new File(o.getPath());
which is throwing the NullPointerException.
Change the above line to :
fls.add(new Option(removeExtension(ff.getName()),"",ff.getPath()));
The "path" from your object "Option" is'nt correct I think.
this line cause the crash :
File file = new File(o.getPath());
on your method "onFileClick".
Try to print o.getPath() to see what's his value, but I think he may be null.