I have a seekbar in my cursor adaptor, code below, when I am playing a song I am supposed to increment it, I have a separate utility class, but the problem is the seekbar is not progressing at all, even if I hard code it, but the log cat is showing my calculations fine which I commented in my run handler.
When I am sliding the seekbar "onStartTrackingTouch" and "onStopTrackingTouch" is responding fine with proper integer value. Music is played via a service which is working fine too.
Where am I going wrong ?
package com.kavayah.spotifystreamer;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.media.Image;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ToggleButton;
import com.kavayah.spotifystreamer.data.SpotifyContract;
import com.squareup.okhttp.Call;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class TrackPlayerAdapter extends CursorAdapter {
private final static String LOG_TAG = TrackPlayerAdapter.class.getSimpleName();
private static Context context;
private SpotifyMusicService mSpotifyMusicService;
private Intent playIntent;
private boolean iSMusicServiceBoundToActivity = false;
private static ServiceConnection spotifyMusicConnection;
private Handler mDurationHandler = new Handler();
private SeekBar mSpotifyMusicSeekBar;
private static int mDuration_ms;
private Utility utils;
//declare a interface which will communicate with the fragment
Callback callback;
public interface Callback {
/**
* DetailFragmentCallback for when an item has been selected.
*/
public void playItemSelected();
public void nextItemSelected(Uri trackUri);
}
/*
public TrackPlayerAdapter(Context context, Cursor c, int flags){
super(context, c, flags);
trackPlayerActivityFragment = new TrackPlayerActivityFragment();
}
*/
public TrackPlayerAdapter(Context context, Cursor c, int flags, Callback callback) {
super(context, c, flags);
this.context = context;
this.callback = callback;
utils = new Utility();
//connect to the service
spotifyMusicConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
SpotifyMusicService.SpotifyMusicBinder binder = (SpotifyMusicService.SpotifyMusicBinder) service;
//get the service
mSpotifyMusicService = binder.getService();
iSMusicServiceBoundToActivity = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
Log.i(LOG_TAG, ">>>>> Music service disconnected.");
iSMusicServiceBoundToActivity = false;
}
};
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
if (playIntent == null) {
playIntent = new Intent(context, SpotifyMusicService.class);
context.bindService(playIntent, spotifyMusicConnection, context.BIND_AUTO_CREATE);
context.startService(playIntent);
}
int viewType = getItemViewType(cursor.getPosition());
int layoutId = -1;
layoutId = R.layout.list_item_player;
View view = LayoutInflater.from(context).inflate(layoutId, parent, false);
TrackPlayerViewHolder trackPlayerViewHolder = new TrackPlayerViewHolder(view);
view.setTag(trackPlayerViewHolder);
return view;
}
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
TrackPlayerViewHolder trackPlayerViewHolder = (TrackPlayerViewHolder) view.getTag();
int viewType = getItemViewType(cursor.getPosition());
String artistIcon = cursor.getString(TrackPlayerActivityFragment.COL_ALBUM_ICON2);
Log.i(LOG_TAG, ">>>>> TrackPlayerActivityFragment.COL_ALBUM_ICON2 " + artistIcon);
if (artistIcon != null && !artistIcon.equals("")) {
Picasso.with(context)
.load(artistIcon)
.memoryPolicy(MemoryPolicy.NO_CACHE)
.networkPolicy(NetworkPolicy.NO_CACHE)
.tag(context)
.into(trackPlayerViewHolder.iconView);
} else {
trackPlayerViewHolder.iconView.setImageResource(0);
}
String artistName = cursor.getString(TrackPlayerActivityFragment.COL_ARTIST_NAME);
trackPlayerViewHolder.artistNameView.setText(artistName);
String albumName = cursor.getString(TrackPlayerActivityFragment.COL_ALBUM_NAME);
trackPlayerViewHolder.albumNameView.setText(albumName);
String trackName = cursor.getString(TrackPlayerActivityFragment.COL_TRACK_NAME);
trackPlayerViewHolder.trackNameView.setText(trackName);
String duration = String.valueOf(cursor.getInt(TrackPlayerActivityFragment.COL_DURATION_MS));
trackPlayerViewHolder.durationView.setText(duration);
//implement the OnSeekBarChangeListener interface methods
mSpotifyMusicSeekBar = (SeekBar) view.findViewById(R.id.musicSeekBar);
mSpotifyMusicSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) {
Log.i("onProgressChanged", "" + progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
Log.i("onStartTrackingTouch",
"" + seekBar.getProgress());
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
Log.i("onStopTrackingTouch",
"" + seekBar.getProgress());
mSpotifyMusicService.seek(seekBar.getProgress());
}
});
final ToggleButton play_button = (ToggleButton) view.findViewById(R.id.media_play);
play_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (view != null) {
Log.i(LOG_TAG, ">>>>> play button click - " + cursor.getInt(TrackPlayerActivityFragment.COL_PRIMARY_TRACK_ID));
//((Callback)trackPlayerActivityFragment).onItemSelected();
callback.playItemSelected();
mSpotifyMusicService.setSongURL(cursor.getString(TrackPlayerActivityFragment.COL_PREVIEW_URL));
mSpotifyMusicService.playSong(cursor.getString(TrackPlayerActivityFragment.COL_TRACK_NAME));
mDuration_ms = cursor.getInt(TrackPlayerActivityFragment.COL_DURATION_MS);
mSpotifyMusicSeekBar.setProgress(0);
mSpotifyMusicSeekBar.setMax(100);
updateSeekbarProgress();
}
}
});
final ImageButton next_button = (ImageButton) view.findViewById(R.id.media_next);
next_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (view != null) {
Integer nextSongId = cursor.getInt(TrackPlayerActivityFragment.COL_PRIMARY_TRACK_ID);
Log.i(LOG_TAG, ">>>>> next button click - " + ++nextSongId);
//check to see if query return null, means it has reached the end of the
// tracks list, stay of the last song even if the user presses next key
Uri nextTrackUri = SpotifyContract.TrackEntry.buildTrackUri(nextSongId);
Cursor cur = context.getContentResolver().query(nextTrackUri, null, null, null, null);
if (cur.getCount() < 1) {
//--nextSongId;
//nextTrackUri = SpotifyContract.TrackEntry.buildTrackUri(nextSongId);
} else {
callback.nextItemSelected(nextTrackUri);
}
if(cur.getCount() > 0){
cur.moveToFirst();
mSpotifyMusicService.setSongURL(cur.getString(TrackPlayerActivityFragment.COL_PREVIEW_URL));
mSpotifyMusicService.playSong(cur.getString(TrackPlayerActivityFragment.COL_TRACK_NAME));
}
//Intent intent = new Intent(context, TrackPlayerActivity.class);
//intent.setData(SpotifyContract.TrackEntry.buildTrackUri(nextSongId));
//context.startActivity(intent);
}
}
});
final ImageButton prev_button = (ImageButton) view.findViewById(R.id.media_prev);
prev_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (view != null) {
Integer prevSongId = cursor.getInt(TrackPlayerActivityFragment.COL_PRIMARY_TRACK_ID);
Log.i(LOG_TAG, ">>>>> prev button click - " + --prevSongId);
//check if the query returns null, means it has reached the beginning
//increment the track id, else it will show null.
Uri prevTrackUri = SpotifyContract.TrackEntry.buildTrackUri(prevSongId);
Cursor cur = context.getContentResolver().query(prevTrackUri, null, null, null, null);
if (cur.getCount() < 1) {
//++prevSongId;
//prevTrackUri = SpotifyContract.TrackEntry.buildTrackUri(prevSongId);
} else {
callback.nextItemSelected(prevTrackUri);
}
if (cur.getCount() > 0) {
cur.moveToFirst();
mSpotifyMusicService.setSongURL(cur.getString(TrackPlayerActivityFragment.COL_PREVIEW_URL));
mSpotifyMusicService.playSong(cur.getString(TrackPlayerActivityFragment.COL_TRACK_NAME));
}
}
}
});
}
public void updateSeekbarProgress(){
mDurationHandler.postDelayed(mUpdateSeekbarTime, 100);
}
private Runnable mUpdateSeekbarTime = new Runnable() {
public void run() {
//long totalDuration = mSpotifyMusicService.getDur();
long currentDuration = mSpotifyMusicService.getPosn();
// Updating progress bar
int progress = (int)(utils.getProgressPercentage(currentDuration, mDuration_ms));
//Log.i(LOG_TAG, " Seekbar position : " + progress);
mSpotifyMusicSeekBar.setProgress(progress);
mDurationHandler.postDelayed(this, 100);
}
};
}
The problem is that you have only one Adapter Object and only one mSpotifyMusicSeekBar variable and bind() is called multiple times, each time for every visible list item.
By the time the Handler is called, the seekBar reference is changed so you never see the progress because some other seekbar is getting updated.
I tried a sample of your code. And here it is - and - seek bar is getting updated as expected:
public class TrackPlayerAdapter extends RecyclerView.Adapter<TrackPlayerAdapter.MyHolder>
{
private final static String TAG = TrackPlayerAdapter.class.getSimpleName();
private Context context;
public TrackPlayerAdapter(Context context)
{
this.context = context;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup viewGroup, int i)
{
LinearLayout container = new LinearLayout(context);
container.setOrientation(LinearLayout.VERTICAL);
container.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams
.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
SeekBar seekbar = new SeekBar(context);
seekbar.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams
.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
Button button = new Button(viewGroup.getContext());
button.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams
.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
button.setText("play");
seekbar.setTag("SEEKBAR");
button.setTag("BUTTON");
container.addView(seekbar);
container.addView(button);
return new MyHolder(container);
}
#Override
public void onBindViewHolder(MyHolder myHolder, int i)
{
myHolder.bind();
}
/**
* Get the row id associated with the specified position in the list.
*
* #param position The position of the item within the adapter's data set whose row id we want.
* #return The id of the item at the specified position.
*/
#Override
public long getItemId(int position)
{
return position;
}
#Override
public int getItemCount()
{
return 3;
}
public static class MyHolder extends RecyclerView.ViewHolder
{
private Handler mDurationHandler = new Handler();
private SeekBar mSpotifyMusicSeekBar;
private Button mToggleButton;
int totalProgress = 0;
public void updateSeekbarProgress()
{
mDurationHandler.postDelayed(mUpdateSeekbarTime, 100);
}
private Runnable mUpdateSeekbarTime = new Runnable()
{
public void run()
{
if(totalProgress <= 10000)
{
totalProgress += 100;
int progress = (int) ((float) totalProgress / 100);
mSpotifyMusicSeekBar.setProgress(progress);
mDurationHandler.postDelayed(this, 1000);
}
}
};
public MyHolder(View itemView)
{
super(itemView);
mSpotifyMusicSeekBar = (SeekBar)itemView.findViewWithTag("SEEKBAR");
mToggleButton = (Button) itemView.findViewWithTag("BUTTON");
}
public void bind()
{
mSpotifyMusicSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
{
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
Log.i(TAG, "onProgressChanged::" + progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar)
{
// TODO Auto-generated method stub
Log.i(TAG, "onStartTrackingTouch::" + seekBar.getProgress());
}
#Override
public void onStopTrackingTouch(SeekBar seekBar)
{
// TODO Auto-generated method stub
Log.i(TAG, "onStopTrackingTouch" + seekBar.getProgress());
}
});
mToggleButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
mSpotifyMusicSeekBar.setProgress(0);
mSpotifyMusicSeekBar.setMax(100);
updateSeekbarProgress();
}
});
}
}
}
Related
When I'm trying to use other RFID SDK to get Tag Code. And send to the server to fetch the tag information. But I only can get the RFID SDK demon working. So I just try to add HTTP request method into the demon. but I always get an error about I'm calling a null object reference. when I use
IAcitivity.IMakeHttpCall();
Inventory Activity
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.uk.tsl.rfid.ModelBase;
import com.uk.tsl.rfid.TSLBluetoothDeviceActivity;
import com.uk.tsl.rfid.WeakHandler;
import com.uk.tsl.rfid.asciiprotocol.AsciiCommander;
import com.uk.tsl.rfid.asciiprotocol.DeviceProperties;
import com.uk.tsl.rfid.asciiprotocol.commands.FactoryDefaultsCommand;
import com.uk.tsl.rfid.asciiprotocol.enumerations.QuerySession;
import com.uk.tsl.rfid.asciiprotocol.enumerations.TriState;
import com.uk.tsl.rfid.asciiprotocol.parameters.AntennaParameters;
import com.uk.tsl.rfid.asciiprotocol.responders.LoggerResponder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class InventoryActivity extends TSLBluetoothDeviceActivity {
// Debug control
private static final boolean D = BuildConfig.DEBUG;
private RequestQueue mVolleyQueue;
// OkHttpClient httpClient = new OkHttpClient();
// The list of results from actions
private ArrayAdapter<String> mResultsArrayAdapter;
private ListView mResultsListView;
private ArrayAdapter<String> mBarcodeResultsArrayAdapter;
private ListView mBarcodeResultsListView;
// The text view to display the RF Output Power used in RFID commands
private TextView mPowerLevelTextView;
// The seek bar used to adjust the RF Output Power for RFID commands
private SeekBar mPowerSeekBar;
// The current setting of the power level
private int mPowerLevel = AntennaParameters.MaximumCarrierPower;
// Error report
private TextView mResultTextView;
// Custom adapter for the session values to display the description rather than the toString() value
public class SessionArrayAdapter extends ArrayAdapter<QuerySession> {
private final QuerySession[] mValues;
public SessionArrayAdapter(Context context, int textViewResourceId, QuerySession[] objects) {
super(context, textViewResourceId, objects);
mValues = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView view = (TextView)super.getView(position, convertView, parent);
view.setText(mValues[position].getDescription());
return view;
}
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
TextView view = (TextView)super.getDropDownView(position, convertView, parent);
view.setText(mValues[position].getDescription());
return view;
}
}
// The session
private QuerySession[] mSessions = new QuerySession[] {
QuerySession.SESSION_0,
QuerySession.SESSION_1,
QuerySession.SESSION_2,
QuerySession.SESSION_3
};
// The list of sessions that can be selected
private SessionArrayAdapter mSessionArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventory);
mVolleyQueue = Volley.newRequestQueue(this);
mResultsArrayAdapter = new ArrayAdapter<String>(this,R.layout.result_item);
mBarcodeResultsArrayAdapter = new ArrayAdapter<String>(this,R.layout.result_item);
mResultTextView = (TextView)findViewById(R.id.resultTextView);
// Find and set up the results ListView
mResultsListView = (ListView) findViewById(R.id.resultListView);
mResultsListView.setAdapter(mResultsArrayAdapter);
mResultsListView.setFastScrollEnabled(true);
mBarcodeResultsListView = (ListView) findViewById(R.id.barcodeListView);
mBarcodeResultsListView.setAdapter(mBarcodeResultsArrayAdapter);
mBarcodeResultsListView.setFastScrollEnabled(true);
// Hook up the button actions
Button sButton = (Button)findViewById(R.id.扫描开始);
sButton.setOnClickListener(mScanButtonListener);
Button cButton = (Button)findViewById(R.id.清除按钮);
cButton.setOnClickListener(mClearButtonListener);
// The SeekBar provides an integer value for the antenna power
mPowerLevelTextView = (TextView)findViewById(R.id.powerTextView);
mPowerSeekBar = (SeekBar)findViewById(R.id.powerSeekBar);
mPowerSeekBar.setOnSeekBarChangeListener(mPowerSeekBarListener);
// Set the seek bar current value to maximum and to cover the range of the power settings
setPowerBarLimits();
mSessionArrayAdapter = new SessionArrayAdapter(this, android.R.layout.simple_spinner_item, mSessions);
// Find and set up the sessions spinner
Spinner spinner = (Spinner) findViewById(R.id.sessionSpinner);
mSessionArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(mSessionArrayAdapter);
spinner.setOnItemSelectedListener(mActionSelectedListener);
spinner.setSelection(0);
// Set up Fast Id check box listener
CheckBox cb = (CheckBox)findViewById(R.id.fastIdCheckBox);
cb.setOnClickListener(mFastIdCheckBoxListener);
//
// An AsciiCommander has been created by the base class
//
AsciiCommander commander = getCommander();
// Add the LoggerResponder - this simply echoes all lines received from the reader to the log
// and passes the line onto the next responder
// This is added first so that no other responder can consume received lines before they are logged.
commander.addResponder(new LoggerResponder());
// Add a synchronous responder to handle synchronous commands
commander.addSynchronousResponder();
//Create a (custom) model and configure its commander and handler
mModel = new InventoryModel();
mModel.setCommander(getCommander());
mModel.setHandler(mGenericModelHandler);
}
#Override
public synchronized void onPause() {
super.onPause();
mModel.setEnabled(false);
// Unregister to receive notifications from the AsciiCommander
LocalBroadcastManager.getInstance(this).unregisterReceiver(mCommanderMessageReceiver);
}
#Override
public synchronized void onResume() {
super.onResume();
mModel.setEnabled(true);
// Register to receive notifications from the AsciiCommander
LocalBroadcastManager.getInstance(this).registerReceiver(mCommanderMessageReceiver,
new IntentFilter(AsciiCommander.STATE_CHANGED_NOTIFICATION));
displayReaderState();
UpdateUI();
}
//----------------------------------------------------------------------------------------------
// Menu
//----------------------------------------------------------------------------------------------
private MenuItem mReconnectMenuItem;
private MenuItem mConnectMenuItem;
private MenuItem mDisconnectMenuItem;
private MenuItem mResetMenuItem;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.reader_menu, menu);
mResetMenuItem = menu.findItem(R.id.reset_reader_menu_item);
mReconnectMenuItem = menu.findItem(R.id.reconnect_reader_menu_item);
mConnectMenuItem = menu.findItem(R.id.insecure_connect_reader_menu_item);
mDisconnectMenuItem= menu.findItem(R.id.disconnect_reader_menu_item);
return true;
}
/**
* Prepare the menu options
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean isConnecting = getCommander().getConnectionState() == AsciiCommander.ConnectionState.CONNECTING;
boolean isConnected = getCommander().isConnected();
mResetMenuItem.setEnabled(isConnected);
mDisconnectMenuItem.setEnabled(isConnected);
mReconnectMenuItem.setEnabled(!(isConnecting || isConnected));
mConnectMenuItem.setEnabled(!(isConnecting || isConnected));
return super.onPrepareOptionsMenu(menu);
}
/**
* Respond to menu item selections
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.reconnect_reader_menu_item:
Toast.makeText(this.getApplicationContext(), "重新连接中...", Toast.LENGTH_LONG).show();
reconnectDevice();
UpdateUI();
return true;
case R.id.insecure_connect_reader_menu_item:
// Choose a device and connect to it
selectDevice();
return true;
case R.id.disconnect_reader_menu_item:
Toast.makeText(this.getApplicationContext(), "断开连接中...", Toast.LENGTH_SHORT).show();
disconnectDevice();
displayReaderState();
return true;
case R.id.reset_reader_menu_item:
resetReader();
UpdateUI();
return true;
}
return super.onOptionsItemSelected(item);
}
//
private void UpdateUI() {
//boolean isConnected = getCommander().isConnected();
//TODO: configure UI control state
}
private void scrollResultsListViewToBottom() {
mResultsListView.post(new Runnable() {
#Override
public void run() {
// Select the last row so it will scroll into view...
mResultsListView.setSelection(mResultsArrayAdapter.getCount() - 1);
}
});
}
private void scrollBarcodeListViewToBottom() {
mBarcodeResultsListView.post(new Runnable() {
#Override
public void run() {
// Select the last row so it will scroll into view...
mBarcodeResultsListView.setSelection(mBarcodeResultsArrayAdapter.getCount() - 1);
}
});
}
//----------------------------------------------------------------------------------------------
// AsciiCommander message handling
//----------------------------------------------------------------------------------------------
//
// Handle the messages broadcast from the AsciiCommander
//
private BroadcastReceiver mCommanderMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (D) { Log.d(getClass().getName(), "AsciiCommander state changed - isConnected: " + getCommander().isConnected()); }
String connectionStateMsg = intent.getStringExtra(AsciiCommander.REASON_KEY);
Toast.makeText(context, connectionStateMsg, Toast.LENGTH_SHORT).show();
displayReaderState();
if( getCommander().isConnected() )
{
// Update for any change in power limits
setPowerBarLimits();
// This may have changed the current power level setting if the new range is smaller than the old range
// so update the model's inventory command for the new power value
mModel.getCommand().setOutputPower(mPowerLevel);
mModel.resetDevice();
mModel.updateConfiguration();
}
UpdateUI();
}
};
//----------------------------------------------------------------------------------------------
// Reader reset
//----------------------------------------------------------------------------------------------
//
// Handle reset controls
//
private void resetReader() {
try {
// Reset the reader
FactoryDefaultsCommand fdCommand = FactoryDefaultsCommand.synchronousCommand();
getCommander().executeCommand(fdCommand);
String msg = "Reset " + (fdCommand.isSuccessful() ? "succeeded" : "failed");
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
UpdateUI();
} catch (Exception e) {
e.printStackTrace();
}
}
//----------------------------------------------------------------------------------------------
// Power seek bar
//----------------------------------------------------------------------------------------------
//
// Set the seek bar to cover the range of the currently connected device
// The power level is set to the new maximum power
//
private void setPowerBarLimits()
{
DeviceProperties deviceProperties = getCommander().getDeviceProperties();
mPowerSeekBar.setMax(deviceProperties.getMaximumCarrierPower() - deviceProperties.getMinimumCarrierPower());
mPowerLevel = deviceProperties.getMaximumCarrierPower();
mPowerSeekBar.setProgress(mPowerLevel - deviceProperties.getMinimumCarrierPower());
}
//
// Handle events from the power level seek bar. Update the mPowerLevel member variable for use in other actions
//
private OnSeekBarChangeListener mPowerSeekBarListener = new OnSeekBarChangeListener() {
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// Nothing to do here
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// Update the reader's setting only after the user has finished changing the value
updatePowerSetting(getCommander().getDeviceProperties().getMinimumCarrierPower() + seekBar.getProgress());
mModel.getCommand().setOutputPower(mPowerLevel);
mModel.updateConfiguration();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
updatePowerSetting(getCommander().getDeviceProperties().getMinimumCarrierPower() + progress);
}
};
private void updatePowerSetting(int level) {
mPowerLevel = level;
mPowerLevelTextView.setText( mPowerLevel + " dBm");
}
//----------------------------------------------------------------------------------------------
// Button event handlers
//----------------------------------------------------------------------------------------------
// Scan action
private OnClickListener mScanButtonListener = new OnClickListener() {
public void onClick(View v) {
try {
mResultTextView.setText("");
// Perform a transponder scan
IMakeHttpCall();
UpdateUI();
} catch (Exception e) {
e.printStackTrace();
}
}
};
// Clear action
private OnClickListener mClearButtonListener = new OnClickListener() {
public void onClick(View v) {
try {
// Clear the list
mResultsArrayAdapter.clear();
mBarcodeResultsArrayAdapter.clear();
UpdateUI();
} catch (Exception e) {
e.printStackTrace();
}
}
};
//----------------------------------------------------------------------------------------------
// Handler for changes in session
//----------------------------------------------------------------------------------------------
private AdapterView.OnItemSelectedListener mActionSelectedListener = new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if( mModel.getCommand() != null ) {
QuerySession targetSession = (QuerySession)parent.getItemAtPosition(pos);
mModel.getCommand().setQuerySession(targetSession);
mModel.updateConfiguration();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
//----------------------------------------------------------------------------------------------
// Handler for changes in FastId
//----------------------------------------------------------------------------------------------
private OnClickListener mFastIdCheckBoxListener = new OnClickListener() {
public void onClick(View v) {
try {
CheckBox fastIdCheckBox = (CheckBox)v;
mModel.getCommand().setUsefastId(fastIdCheckBox.isChecked() ? TriState.YES : TriState.NO);
mModel.updateConfiguration();
UpdateUI();
} catch (Exception e) {
e.printStackTrace();
}
}
};
public void IMakeHttpCall(){
String url = "http://192.168.1.76:4300/lottem/query/toolsstockInventory/";
Uri.Builder builder = Uri.parse(url).buildUpon();
builder.appendQueryParameter("barCode", "1121212121");
JsonArrayRequest jsonObjRequest = new JsonArrayRequest(builder.toString(),
new Response.Listener<JSONArray>(){
#Override
public void onResponse(JSONArray response) {
try {
JSONObject person;
for (int i = 0; i < response.length(); i++) {
person = response.getJSONObject(i);
String name = person.getString(("toolsName"));
mResultTextView.setText(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// Handle your error types accordingly.For Timeout & No connection error, you can show 'retry' button.
// For AuthFailure, you can re login with user credentials.
// For ClientError, 400 & 401, Errors happening on client side when sending api request.
// In this case you can check how client is forming the api and debug accordingly.
// For ServerError 5xx, you can do retry or handle accordingly.
if (error instanceof NetworkError) {
} else if (error instanceof ServerError) {
} else if (error instanceof AuthFailureError) {
} else if (error instanceof ParseError) {
} else if (error instanceof NoConnectionError) {
} else if (error instanceof TimeoutError) {
}
}
});
//Set a retry policy in case of SocketTimeout & ConnectionTimeout Exceptions. Volley does retry for you if you have specified the policy.
mVolleyQueue.add(jsonObjRequest);
}
}
InventoryModel
//----------------------------------------------------------------------------------------------
// Copyright (c) 2013 Technology Solutions UK Ltd. All rights reserved.
//----------------------------------------------------------------------------------------------
package com.uk.tsl.rfid.samples.inventory;
import android.util.Log;
import com.uk.tsl.rfid.ModelBase;
import com.uk.tsl.rfid.asciiprotocol.commands.BarcodeCommand;
import com.uk.tsl.rfid.asciiprotocol.commands.FactoryDefaultsCommand;
import com.uk.tsl.rfid.asciiprotocol.commands.InventoryCommand;
import com.uk.tsl.rfid.asciiprotocol.enumerations.TriState;
import com.uk.tsl.rfid.asciiprotocol.responders.IBarcodeReceivedDelegate;
import com.uk.tsl.rfid.asciiprotocol.responders.ICommandResponseLifecycleDelegate;
import com.uk.tsl.rfid.asciiprotocol.responders.ITransponderReceivedDelegate;
import com.uk.tsl.rfid.asciiprotocol.responders.TransponderData;
import com.uk.tsl.utils.HexEncoding;
import java.util.Locale;
public class InventoryModel extends ModelBase
{
// Control
private boolean mAnyTagSeen;
private boolean mEnabled;
public boolean enabled() { return mEnabled; }
private InventoryActivity IAcitivity;
public void setEnabled(boolean state)
{
boolean oldState = mEnabled;
mEnabled = state;
// Update the commander for state changes
if(oldState != state) {
if( mEnabled ) {
// Listen for transponders
getCommander().addResponder(mInventoryResponder);
// Listen for barcodes
getCommander().addResponder(mBarcodeResponder);
} else {
// Stop listening for transponders
getCommander().removeResponder(mInventoryResponder);
// Stop listening for barcodes
getCommander().removeResponder(mBarcodeResponder);
}
}
}
// The command to use as a responder to capture incoming inventory responses
private InventoryCommand mInventoryResponder;
// The command used to issue commands
private InventoryCommand mInventoryCommand;
// The command to use as a responder to capture incoming barcode responses
private BarcodeCommand mBarcodeResponder;
// The inventory command configuration
public InventoryCommand getCommand() { return mInventoryCommand; }
public InventoryModel()
{
// This is the command that will be used to perform configuration changes and inventories
mInventoryCommand = new InventoryCommand();
mInventoryCommand.setResetParameters(TriState.YES);
// Configure the type of inventory
mInventoryCommand.setIncludeTransponderRssi(TriState.YES);
mInventoryCommand.setIncludeChecksum(TriState.YES);
mInventoryCommand.setIncludePC(TriState.YES);
mInventoryCommand.setIncludeDateTime(TriState.YES);
// Use an InventoryCommand as a responder to capture all incoming inventory responses
mInventoryResponder = new InventoryCommand();
// Also capture the responses that were not from App commands
mInventoryResponder.setCaptureNonLibraryResponses(true);
// Notify when each transponder is seen
mInventoryResponder.setTransponderReceivedDelegate(new ITransponderReceivedDelegate() {
int mTagsSeen = 0;
#Override
public void transponderReceived(final TransponderData transponder, boolean moreAvailable) {
mAnyTagSeen = true;
final String tidMessage = transponder.getTidData() == null ? "" : HexEncoding.bytesToString(transponder.getTidData());
final String infoMsg = String.format(Locale.US, "\nRSSI: %d PC: %04X CRC: %04X", transponder.getRssi(), transponder.getPc(), transponder.getCrc());
IAcitivity.IMakeHttpCall();
sendMessageNotification("条形码:"+transponder.getEpc());
mTagsSeen++;
if( !moreAvailable) {
sendMessageNotification("");
Log.d("扫描次数",String.format("扫描到的次数: %s", mTagsSeen));
}
}
});
}
Here is my code:
package com.saba.admin.w2track;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import Adapters.VehicleListAdapter;
import Model.UserData;
import Model.VehicleData;
public class DashboardActivity extends AppCompatActivity {
static ArrayList<VehicleData> vehicleArrayList=new ArrayList<>();
static ArrayList<VehicleData> vehicleArrayList1=new ArrayList<>();
boolean clearflag=false;
static ArrayList<VehicleData> vehicleArrayListMoving=new ArrayList<>();
static ArrayList<VehicleData> vehicleArrayListStopped=new ArrayList<>();
static ArrayList<VehicleData> vehicleArrayListActive=new ArrayList<>();
static ArrayList<VehicleData> vehicleArrayListInActive=new ArrayList<>();
String acctype;
//static VehicleListAdapter listAdapter;
UserData userData;
TextView txtStopped,txtMoving,txtTotal,txtInactive,txtAlerts;
RelativeLayout moving,alerts,inactive,stopped,total;
boolean doubleBackToExitPressedOnce = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard3);
setView();
getBundleData();
// String acc[]={acctype};
updateVehicles();
}
public void updateVehicles() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
DashboardActivity.this.runOnUiThread(new Runnable() {
public void run() {
try {
vehicle v = new vehicle();
v.execute(acctype);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 30000);
}
public void setView(){
txtStopped=(TextView)findViewById(R.id.txtstopped);
txtMoving=(TextView)findViewById(R.id.txtmoving);
txtAlerts=(TextView)findViewById(R.id.txtalerts);
txtInactive=(TextView)findViewById(R.id.txtinactive);
txtTotal=(TextView)findViewById(R.id.txttotal);
moving=(RelativeLayout)findViewById(R.id.LayoutMoving);
stopped=(RelativeLayout)findViewById(R.id.LayoutStopped);
alerts=(RelativeLayout)findViewById(R.id.LayoutAlerts);
inactive=(RelativeLayout)findViewById(R.id.LayoutInActive);
total=(RelativeLayout)findViewById(R.id.LayoutTotal);
}
public void getBundleData(){
Bundle b = getIntent().getExtras();
if (b != null && b.containsKey("userData"))
{
userData=b.getParcelable("userData");
acctype=b.getString("acctype");
// Log.d("accountid",userData.getAccountId()+" ");
Log.d("userid123..",userData.getUserId()+" ");
Log.d("timediff123..",userData.getTimediff()+" ");
//Log.d("km1..",userData.getMilesPerKms()+" ");
}
}
//vehicle asyncclass in dashboard..which is called in dashboard every 30 sec to get updated data & store in arraylist.
private class vehicle extends AsyncTask<String,String,String> {
private ProgressDialog dialog;
String response="";
private JSONObject res;
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
if(!DashboardActivity.this.isFinishing()) {
dialog = new ProgressDialog(DashboardActivity.this);
dialog.setMessage("Please Wait..");
dialog.setCancelable(false);
// searchBox.setEnabled(false);
dialog.show();
}
if(true) {
vehicleArrayList.clear();
vehicleArrayList1.clear();
vehicleArrayListMoving.clear();
vehicleArrayListStopped.clear();
vehicleArrayListActive.clear();
vehicleArrayListInActive.clear();
Log.d("cleared1111", "cleared ");
clearflag=true;
}
}catch (Exception e){
Log.d("eroror1111", e.toString() + " ");
// Toast.makeText(getActivity(),e.toString(),Toast.LENGTH_SHORT).show();
}
}
#Override
protected String doInBackground(String... params) {
try {
JSONObject vehicle_json = new JSONObject();
vehicle_json.put("pAccountId", userData.getUserId());
res = CustomHttpClient.postJsonObject("http://"+params[0]+".w2track.com/api/index.php?cmd=vehicles", vehicle_json,DashboardActivity.this);
String resData=res.getString("ResponseData");
JSONArray array=new JSONArray(resData);
Log.d("1111",array.length()+" ");
for(int i=0;i<array.length();i++){
Log.d("11112","2222");
VehicleData vehicleData=new VehicleData();
JSONObject jsonVehicleObj=new JSONObject(array.get(i).toString());
Log.d("111123", "2222");
if(jsonVehicleObj.getString("vehiclenumber").equals("null") ||jsonVehicleObj.getString("vehiclenumber")==null ){
Log.d("111124","2222");
continue;
// Log.d("11112","2222");
}
vehicleData.setVehicleNumber(jsonVehicleObj.getString("vehiclenumber"));
vehicleData.setPlacename(jsonVehicleObj.getString("location"));
vehicleData.setSpeed(jsonVehicleObj.getString("speed"));
vehicleData.setLandmark(jsonVehicleObj.getString("landmark"));
vehicleData.setIsActive(jsonVehicleObj.getBoolean("isactive"));
vehicleData.setVehicleType(jsonVehicleObj.getString("vehicletype"));
vehicleData.setFuel(jsonVehicleObj.getString("fuel"));
Log.d("fuel11115", vehicleData.getFuel() + " ");
vehicleData.setDept(jsonVehicleObj.getString("department"));
vehicleData.setDivision(jsonVehicleObj.getString("division"));
vehicleData.setIginition(jsonVehicleObj.getString("ignition"));
vehicleData.setLati(jsonVehicleObj.getString("lat"));
vehicleData.setLongi(jsonVehicleObj.getString("lng"));
vehicleData.setOdometer(jsonVehicleObj.getString("odometer"));
vehicleData.setGpsmode(jsonVehicleObj.getString("gpsmode"));
vehicleData.setInnerbattery(jsonVehicleObj.getDouble("inbatt"));
vehicleData.setExtbattery(jsonVehicleObj.getDouble("extbatt"));
vehicleData.setUnitId(jsonVehicleObj.getString("unitid"));
vehicleData.setUnitNo(jsonVehicleObj.getString("unitno"));
vehicleData.setIgnitionTime(jsonVehicleObj.getString("ign_time"));
vehicleData.setDate1(jsonVehicleObj.getString("date"));
vehicleData.setIconImage(jsonVehicleObj.getString("icon"));
vehicleData.setSignal(jsonVehicleObj.getString("signal"));
Log.d("111126", "2222");
if(clearflag) {
vehicleArrayList.add(vehicleData);
vehicleArrayList1.add(vehicleData);
Log.d("111127", "2222");
if (vehicleData.getIginition().equals("Off") && vehicleData.isActive()) {
vehicleArrayListStopped.add(vehicleData);
vehicleArrayListActive.add(vehicleData);
} else if (vehicleData.getIginition().equals("On") && vehicleData.isActive()) {
vehicleArrayListMoving.add(vehicleData);
vehicleArrayListActive.add(vehicleData);
} else if (!vehicleData.isActive()) {
vehicleArrayListInActive.add(vehicleData);
}
}
Log.d("vehicleno1111",vehicleData.getVehicleNumber()+" ");
}
clearflag=false;
// JSONObject jsonObject1=new JSONObject(array.get(0).toString());
// response=jsonObject1.toString();
//Log.d("myresponse",response+" ");
}catch (Exception e){
Log.d("errorrrr1111", e.toString());
}
return response;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
txtTotal.setText("Total ("+ vehicleArrayList.size()+")");
txtMoving.setText("Moving ("+ vehicleArrayListMoving.size()+")");
txtStopped.setText("Stopped ("+vehicleArrayListStopped.size()+")");
// txtAlerts.setText(jsonObject.getString("TotalActive"));
txtInactive.setText("InActive (" + vehicleArrayListInActive.size() + ")");
if(!DashboardActivity.this.isFinishing()) {
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
}
//dashboard activty calls vehicle service every 30 seconds & storing in different arraylist like moving, stopped etc. i am using that arraraylist & settting adapter & calling notifydatasetchanged (every 10 sec) in vehicle activity
VehicleList class
public class VehicleList extends android.support.v4.app.Fragment {
Runnable r;
Timer timer;
TimerTask myTimerTask;
ListView lstVehicle;
EditText searchBox;
static String status;
// Context context;
VehicleListActivityFinal vehicleListActivityFinal;
ImageView img;
static UserData userData;
int accid,timdiff,mile;
String userid,acctype;
VehicleListAdapter listAdapter;
final Handler handler =new Handler() ;
VehicleListActivityFinal vehiclefinal;
}*/
public VehicleList() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("oncreate..", "oncreate..");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view= inflater.inflate(R.layout.fragment_vehicle_list, container, false);
//vehicleArrayList =new ArrayList<VehicleData>();
lstVehicle =(ListView)view.findViewById(R.id.vehicle_listview);
// lstVehicle.requestFocus();
img=(ImageView)view.findViewById(R.id.Imgnodata);
Log.d("createview", "createview");
if (getArguments() != null) {
// Bundle bundle=getArguments();
userid=getArguments().getString("UserID");
acctype=getArguments().getString("acctype");
timdiff=getArguments().getInt("TimeDiff");
status=getArguments().getString("status");
Log.d("arg1111",userid+" ");
Log.d("arg11112",timdiff+" ");
}
else
{
Log.d("insidenull","nullnull");
}
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
vehicleListActivityFinal=(VehicleListActivityFinal)getActivity();
searchBox=(EditText)vehicleListActivityFinal.findViewById(R.id.searchBox);
Log.d("onactivitycrated..", "activitycreated...");
if(savedInstanceState==null) {
if (CheckInternet.isConnectionAvailable(vehicleListActivityFinal)) {
getVehicleData();
updateVehicleData();
} else {
CheckInternet.showNoInternet(vehicleListActivityFinal);
}
}
Log.d("testtest", vehicleListActivityFinal.test + " ");
lstVehicle.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try {
VehicleData vehicleData = (VehicleData) parent.getAdapter().getItem(position);
Intent intent = new Intent(vehicleListActivityFinal, VehicleDetailActivity.class);
intent.putExtra("vehicleData1", vehicleData);
intent.putExtra("acctype", acctype);
// intent.putExtra()
startActivity(intent);
vehicleListActivityFinal.overridePendingTransition(R.anim.push_in, R.anim.push_out);
}catch (Exception e){
Toast.makeText(vehicleListActivityFinal,e.toString(),Toast.LENGTH_SHORT).show();
}
}
});
searchText();
// updateVehicleData();
// setRetainInstance(true);
}
//method which calls notifydatasetchanged every 10 seconds on vehicle activity
public void updateVehicleData(){
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
vehicleListActivityFinal.runOnUiThread(new Runnable() {
public void run() {
try {
// getVehicleData();
img.setVisibility(View.GONE);
listAdapter.notifyDataSetChanged();
lstVehicle.invalidate();
if (lstVehicle.getAdapter().getCount() == 0) {
img.setVisibility(View.VISIBLE);
Toast.makeText(vehicleListActivityFinal, "empty list..", Toast.LENGTH_SHORT).show();
}
Toast.makeText(vehicleListActivityFinal, "Refreshing Data..", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 10000);
}
method which sets adapter of vehicle on vehicle activity
public void getVehicleData(){
// lstVehicle.requestFocus();
if(VehicleListActivityFinal.movingStatus.equals("moving")) {
listAdapter = new VehicleListAdapter(vehicleListActivityFinal, DashboardActivity.vehicleArrayListMoving,vehicleListActivityFinal);
// Log.d("adapterempty", listAdapter.isEmpty()+" ");
lstVehicle.setAdapter(listAdapter);
//listAdapter.notifyDataSetChanged();
}
else if(VehicleListActivityFinal.movingStatus.equals("total")){
listAdapter = new VehicleListAdapter(vehicleListActivityFinal, DashboardActivity.vehicleArrayList1,vehicleListActivityFinal);
lstVehicle.setAdapter(listAdapter);
//listAdapter.notifyDataSetChanged();
}
else if(VehicleListActivityFinal.movingStatus.equals("inactive")){
listAdapter = new VehicleListAdapter(vehicleListActivityFinal, DashboardActivity.vehicleArrayListInActive,vehicleListActivityFinal);
lstVehicle.setAdapter(listAdapter);
//listAdapter.notifyDataSetChanged();
}
else if(VehicleListActivityFinal.movingStatus.equals("stopped")){
listAdapter = new VehicleListAdapter(vehicleListActivityFinal, DashboardActivity.vehicleArrayListStopped,vehicleListActivityFinal);
lstVehicle.setAdapter(listAdapter);
// listAdapter.notifyDataSetChanged();
}
else
{
listAdapter = new VehicleListAdapter(vehicleListActivityFinal, DashboardActivity.vehicleArrayList1,vehicleListActivityFinal);
lstVehicle.setAdapter(listAdapter);
// listAdapter.notifyDataSetChanged();
}
// lstVehicle.invalidate();
//lstVehicle.requestLayout();
Log.d("postexecute1111", searchBox.isFocused() + " ");
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
VehicleListActivityFinal.currentFragment="VehicleList";
}
#Override
public void onDetach() {
super.onDetach();
Log.d("detach1", "detach");
}
#Override
public void onResume() {
super.onResume();
Log.d("onresume", "onresume");
}
public void searchText() {
// lstVehicle.setAdapter(listAdapter);
searchBox.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
Toast.makeText(vehicleListActivityFinal,"beforetextchanged",Toast.LENGTH_SHORT).show();
}
#Override
public void onTextChanged(CharSequence s1, int start, int before, int count) {
listAdapter.getFilter().filter(s1.toString());
// Toast.makeText(getActivity(),"ontextchanged",Toast.LENGTH_SHORT).show();
//lstVehicle.setAdapter(listAdapter);
//listAdapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(Editable s) {
//Toast.makeText(getActivity(),"afterrtextchanged",Toast.LENGTH_SHORT).show();
}
});
}
}
I am making a slot machine app and using kankan's wheel for the same. I want to modify the library such that when the rotation stops the item it will point shoud be the one that I set . I have done this but there is a glitch that shows that we have changed the actual image to the one that we want . How to achieve this?
Update:
I have researched a lot on this and if I am right , android scroll is based on duration and distance not items . From kankan's wheel library I can get current item .Now , I am trying to stop the animation as well as scroll , as soon as a certain duration has been reached and the item is the one that I want (through index) . But this is not working .Please help!!
GameActivity
public class GameActivity extends Activity {
float mDeviceDensity;
String mUuid, mTitle, mContent, mReward;
ImageButton play;
SlotMachineAdapter slotAdapter;
private List<HashMap<String, Object>> slotImages = new ArrayList<HashMap<String, Object>>();
ArrayList<String> imagesWinId = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_filler_up_game);
DisplayMetrics display = getResources().getDisplayMetrics();
mDeviceDensity = display.density;
slotAdapter = new SlotMachineAdapter(this);
getPassedData();
setSoundPlayer(R.raw.clicks,true);
initWheel(R.id.slot_1, false, 0);
initWheel(R.id.slot_2, false, 1);
initWheel(R.id.slot_3, true, 2);
play = (ImageButton) findViewById(R.id.btn_mix);
play.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
shuffle(R.id.slot_1, 5000);
shuffle(R.id.slot_2, 7000);
shuffle(R.id.slot_3, 9000);
}
});
}
protected ImageLoader imageLoader;
ArrayList<SlotItem> arrListSlotItems;
private void getPassedData() {
try {
mUuid = getIntent().getStringExtra(getString(R.string.FILLER_UP_UUID));
imageLoader = ImageLoader.getInstance();
Uuid slotImagesExtra = (Uuid) (getIntent()
.getSerializableExtra(getString(R.string.FILLER_UP_IMAGES)));
arrListSlotItems = slotImagesExtra.getArrSlotItemArray();
for (int i = 0; i < arrListSlotItems.size(); i++)
downloadSlotImages(arrListSlotItems.get(i).getSlotId(), arrListSlotItems.get(i).getImageUrl());
} catch (Exception e) {
e.printStackTrace();
}
}
// Wheel scrolled flag
private boolean wheelScrolled = false;
// Wheel scrolled listener
OnWheelScrollListener scrolledListener = new OnWheelScrollListener() {
public void onScrollingStarted(WheelView wheel) {
wheelScrolled = true;
}
public void onScrollingFinished(WheelView wheel) {
wheelScrolled = false;
setStatus(wheel.getId(), getWheel(wheel.getId()).getWinningIndex());
}
};
// Wheel changed listener
private OnWheelChangedListener changedListener = new OnWheelChangedListener() {
public void onChanged(WheelView wheel, int oldValue, int newValue) {
if (!wheelScrolled) {
}
}
};
/**
* Updates status
*/
private void updateStatus() {
myThread();
}
public void myThread(){
Thread th=new Thread(){
#Override
public void run(){
try
{
Thread.sleep(2000);
GameActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
showAlertDialogWithSingleButton(GameActivity.this, mTitle, mContent, success);
}
});
}catch (InterruptedException e) {
// TODO: handle exception
}
}
};
th.start();
}
android.content.DialogInterface.OnClickListener success = new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (mContent != null && mContent.contains("again"))
startHomeActivity();
else
startNewsActivity();
}
};
private void startHomeActivity() {
}
private void startNewsActivity() {
}
android.content.DialogInterface.OnClickListener fail = new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//
}
};
public void showAlertDialogWithSingleButton(final Activity ctx, final String title, final String message,
DialogInterface.OnClickListener onClickListener) {
// show dialog
}
private void initWheel(int id, boolean monitorScroll, int itemIndex) {
Random randomGenerator = new Random();
int index = randomGenerator.nextInt(arrListSlotItems.size());
WheelView wheel = getWheel(id);
wheel.setViewAdapter(slotAdapter);
wheel.setCurrentItem((index ));
wheel.setVisibleItems(1);
wheel.setWinningIndex(itemIndex);
wheel.addChangingListener(changedListener);
wheel.addScrollingListener(scrolledListener);
wheel.setCyclic(true);
wheel.setEnabled(false);
}
private WheelView getWheel(int id) {
return (WheelView) findViewById(id);
}
private void setStatus(int id, int item) {
int index = 0;
for (int i = 0; i < arrListSlotItems.size(); i++) {
SlotItem d = arrListSlotItems.get(i);
if (d.getSlotId() != 0 && d.getSlotId() == Integer.parseInt(imagesWinId.get(item)))
index = arrListSlotItems.indexOf(d);
}
getWheel(id).setCurrentItem(index, true);
if (id == R.id.slot_3) {
if(player.isPlaying())
{
stopBackgroundAudio();
}
updateStatus();
}
}
private void shuffle(int id, int duration) {
WheelView wheel = getWheel(id);
wheel.scroll(450 + (int) (Math.random() * 50), duration);
}
private class SlotMachineAdapter extends AbstractWheelAdapter {
final int IMAGE_WIDTH = getImageWidth(mDeviceDensity);
final int IMAGE_HEIGHT = getImageHeight(mDeviceDensity);
private Context context;
/**
* Constructor
*/
public SlotMachineAdapter(Context context) {
this.context = context;
}
/**
* Loads image from resources
*/
private Bitmap loadImage(Bitmap bitmap) {
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, IMAGE_WIDTH, IMAGE_HEIGHT, true);
return scaled;
}
#Override
public int getItemsCount() {
return slotImages.size();
}
// Layout params for image view
final LayoutParams params = new LayoutParams(IMAGE_WIDTH, IMAGE_HEIGHT);
#Override
public View getItem(int index, View cachedView, ViewGroup parent) {
ImageView img;
if (cachedView != null) {
img = (ImageView) cachedView;
} else {
img = new ImageView(context);
}
img.setPadding(0, 5, 0, 5);
img.setLayoutParams(params);
#SuppressWarnings("unchecked")
SoftReference<Bitmap> bitmapRef = (SoftReference<Bitmap>) slotImages.get(index).get("image");
Bitmap bitmap = bitmapRef.get();
if (bitmap == null) {
bitmap = loadImage(bitmap);
}
img.setImageBitmap(bitmap);
return img;
}
}
private int getImageWidth(float density) {
}
private int getImageHeight(float density) {
}
private void downloadSlotImages(final int id, String slotObj) {
//downloading slot images from server
}
}
This is the code. Through this code, when slot stops I want it to scroll some more untill it reaches the image position that I receaved from server. I can do this .But this is providing a lil glitch . Is there any way to stop scrolling when the image is reached as soon as certain duration is reached.
P.S. If you need anymore detail I can provide you.
P.P.S. Screenshots wont give you any detailed insight about the issue.
After days of searching I finally did it.All I had to do was set interpolater as LinearInterpolater and While setting setCurrentItem set animation as true.
I am having an issue with a Fragment and an AsyncTask. The issue is that I am creating a Fragment to run an AsyncTask to run a timer. The code works independently of all my other code and I have tested it numerous times. The issue is that when I place my new code into my app, I get a null pointer at this point:
public void onClick(View v) {
if(v==abbtn){
aboutFragDialog();
}else if(v==exbtn){
finish();
}else if(v==starest){
if(mTaskFragment.isRunning()){
mTaskFragment.cancel();
} else {
mTaskFragment.start();
}if(v==mgextbtn){
mgcusd.dismiss();
}
}
}
the actual line that is pushing the error is: if(mTaskFragment.isRunning()){. This code links to the following:
public void replaceFrag(){
Bundle bundle = new Bundle();
String tester2 = String.valueOf(startTime).toString();
Log.i("VertygoEclypse - replaceFrag - Value for counter ", tester2);
if(tester2.matches("")){
bundle.putString("SecValue", "15");
} else {
bundle.putString("SecValue", tester2);
}
FragmentManager rfm = getSupportFragmentManager();
if(mTaskFragment == null){
TaskFragment mTaskFragment = new TaskFragment();
mTaskFragment.setArguments(bundle);
rfm.beginTransaction().add(mTaskFragment, "task").commit();
} else {
TaskFragment mTaskFragment = new TaskFragment();
mTaskFragment = (TaskFragment) rfm.findFragmentByTag("task");
mTaskFragment.setArguments(bundle);
rfm.beginTransaction().add(mTaskFragment, "task").commit();
}
}
which gets called from the following:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
switch(parent.getId()){
case R.id.timerspinner:
TimerDataBaseHandler isdb = new TimerDataBaseHandler(getApplicationContext());
SQLiteDatabase dbsec = isdb.getReadableDatabase();
int tagposition = s.getSelectedItemPosition()+1;
isdb.getReadableDatabase();
Cursor cc = dbsec.rawQuery("SELECT * FROM timers WHERE _id = "+tagposition, null);
if(cc.moveToFirst()){
setTimer(Integer.parseInt(cc.getString(2)));
starest.setEnabled(true);
replaceFrag();
}
}
}
the above code is enough that in my TaskFragment Activity with Logs I can see that the variable I send across is being seen to be used as a startTime for a count down which is here:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
bundle=getArguments();
i = bundle.getString("SecValue");
Log.i("VertygoEclypse - TaskFragment-onCreate", i);
counter=Integer.parseInt(i);
Log.i("VertygoEclypse - TaskFragment - onCreate", String.valueOf(counter).toString());
}
that being said, this code works as a stand alone and works and gives the expected results. The issue is when I wire it up to work with my app, it seems that although the value moves across to the Fragment I cannot start the Asynctask. Below is my code so far.
This is the TaskFragment.class
package com.vertygoeclypse.multitimer;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.util.Log;
public class TaskFragment extends Fragment {
private static final String TAG = TaskFragment.class.getSimpleName();
String i;
static int counter, validcounter;
Bundle bundle;
static interface TaskCallbacks {
public void onPreExecute();
public void onProgressUpdate(int timer);
public void onCancelled();
public void onPostExecute();
}
private TaskCallbacks mCallbacks;
private DummyTask mTask;
private boolean mRunning;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof TaskCallbacks)) {
throw new IllegalStateException("Activity must implement the TaskCallbacks interface.");
}
mCallbacks = (TaskCallbacks) activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
bundle=getArguments();
i = bundle.getString("SecValue");
Log.i("VertygoEclypse - TaskFragment-onCreate", i);
counter=Integer.parseInt(i);
Log.i("VertygoEclypse - TaskFragment - onCreate", String.valueOf(counter).toString());
}
#Override
public void onDestroy() {
super.onDestroy();
cancel();
}
public void start() {
if (!mRunning) {
Log.i("VertygoEclypse - TaskFragment - start", String.valueOf(counter).toString());
mTask = new DummyTask();
validcounter = counter;
Log.i("VertygoEclypse - TaskFragment - validcounter", String.valueOf(validcounter).toString());
mTask.execute();
mRunning = true;
} else{
mTask.cancel(true);
}
}
public void cancel() {
if (mRunning) {
mTask.cancel(true);
mTask = null;
mRunning = false;
}
}
public boolean isRunning() {
return mRunning;
}
private class DummyTask extends AsyncTask<Void, Integer, Void> {
#Override
protected void onPreExecute() {
mCallbacks.onPreExecute();
mRunning = true;
Log.i("Vertygo Eclypse - AsyncTask - onPreExecute", i);
}
#Override
protected Void doInBackground(Void... ignore) {
Log.i("Vertygo Eclypse - AsyncTask - onPreExecute", String.valueOf(validcounter).toString());
do {
publishProgress(validcounter);
SystemClock.sleep(1000);
validcounter=validcounter-1;
if(isCancelled()){
mTask.cancel(true);
break;
}
} while (validcounter>0);
return null;
}
#Override
protected void onProgressUpdate(Integer... timer) {
mCallbacks.onProgressUpdate(timer[0]);
}
#Override
protected void onCancelled() {
mCallbacks.onCancelled();
mRunning = false;
}
#Override
protected void onPostExecute(Void ignore) {
mCallbacks.onPostExecute();
mRunning = false;
}
}
}
the MainActivity is kinda long so I hope no one gets upset, but I think without seeing the code, a proper assessment can not be made.
package com.vertygoeclypse.multitimer;
//--------------------------------------------------------------------------------------------------
import android.app.Dialog;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Vibrator;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.Spinner;
import android.widget.TextView;
import com.vertygoeclypse.multitimer.AddDialog.onSubmitListener;
import com.vertygoeclypse.multitimer.UpdateDialog.onSubmitUpdateListener;
import java.io.File;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static android.widget.AdapterView.OnItemSelectedListener;
//--------------------------------------------------------------------------------------------------
public class MainActivity extends FragmentActivity implements NumberPicker.OnValueChangeListener, OnClickListener, OnItemSelectedListener, onSubmitListener, onSubmitUpdateListener, TaskFragment.TaskCallbacks {
//--------------------------------------------------------------------------------------------------
Button abbtn, exbtn, starest, mgextbtn;
TextView timeRemaining;
Dialog mgcusd;
Typeface tf;
Spinner s;
Vibrator v;
protected CountDownTimer timerCountDownTimer;
Handler timerHandler = new Handler();
public boolean timerHasStarted = false;
protected int startTime=0;
protected int val1, val2, val3, val4, temp1, upposval, validcounter;
protected String tagval1, temp2, uptagval, uptimeval;
boolean savechkbx=true;
File mydb ;
public static Context PACKAGE_NAME;
private static final String TIME_COUNT = "time_count";
private TaskFragment mTaskFragment;
//--------------------------------------------------------------------------------------------------
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//--------------------------------------------------------------------------------------------------
PACKAGE_NAME = getApplicationContext();
TimerDataBaseHandler db = new TimerDataBaseHandler(getApplicationContext());
mydb = new File("/data/data/com.vertygoeclypse.multitimer/databases/TimerManager");
if(mydb.exists()){
} else {
db.addTimer(new TimerClass("Lipton", "180"));
}
//--------------------------------------------------------------------------------------------------
abbtn = (Button) findViewById(R.id.aboutbtn);
exbtn = (Button) findViewById(R.id.exitbtn);
starest = (Button) findViewById(R.id.startresetbtn);
timeRemaining = (TextView) findViewById(R.id.timeremainingview);
s = (Spinner)findViewById(R.id.timerspinner);
tf = Typeface.createFromAsset(getAssets(),"digital7.ttf");
v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
//--------------------------------------------------------------------------------------------------
abbtn.setOnClickListener(this);
exbtn.setOnClickListener(this);
starest.setOnClickListener(this);
s.setOnItemSelectedListener(this);
//--------------------------------------------------------------------------------------------------
if(startTime==0){
starest.setEnabled(false);
}else if(startTime>0){
starest.setEnabled(true);
starest.setTextColor(getResources().getColor(android.R.color.primary_text_light));
}
LoadSpinnerData();
if (savedInstanceState != null) {
timeRemaining.setTypeface(tf);
timeRemaining.setText(savedInstanceState.getString(TIME_COUNT));
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(TIME_COUNT, timeRemaining.getText().toString());
}
//--------------------------------------------------------------------------------------------------
public void LoadSpinnerData(){
TimerDataBaseHandler tdb = new TimerDataBaseHandler(getApplicationContext());
List<String> timerlabels = tdb.fetchAllTimers();
ArrayAdapter<String> dataAdapter;
dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, timerlabels);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(dataAdapter);
}
public void mgLoadSpinnerData(){
TimerDataBaseHandler updb = new TimerDataBaseHandler(getApplicationContext());
List<String> updatetimers = updb.fetchAllTimers();
ArrayAdapter<String> dataAdapter;
dataAdapter = new ArrayAdapter<String>(this, R.layout.customer_colored_spinner_item, updatetimers);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
UpdateDialog.mgs.setAdapter(dataAdapter);
}
//--------------------------------------------------------------------------------------------------
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {}
//--------------------------------------------------------------------------------------------------
public static String getDurationBreakdown(long secondstobreak) {
if(secondstobreak < 0)
{
throw new IllegalArgumentException("Duration must be greater than zero!");
}
long hours = TimeUnit.MILLISECONDS.toHours(secondstobreak);
secondstobreak-=TimeUnit.HOURS.toMillis(hours);
long minutes = TimeUnit.MILLISECONDS.toMinutes(secondstobreak);
secondstobreak-=TimeUnit.MINUTES.toMillis(minutes);
long seconds = TimeUnit.MILLISECONDS.toSeconds(secondstobreak);
secondstobreak-=TimeUnit.SECONDS.toMillis(seconds);
StringBuilder sb = new StringBuilder(64);
if(hours<10){
sb.append("0"+hours);
}else {
sb.append(hours);
}
sb.append(" : ");
if(minutes<10){
sb.append("0"+minutes);
}else{
sb.append(minutes);
}
sb.append(" : ");
if(seconds<10){
sb.append("0"+seconds);
} else {
sb.append(seconds);
}
sb.append(" remaining");
return (sb.toString());
}
//--------------------------------------------------------------------------------------------------
public void setTimer(int minutes) {
if(timerHasStarted)
return;
startTime = minutes;
if(startTime < 1)
startTime = 1;
long val6 = (long)startTime*1000;
String ststring = getDurationBreakdown(val6);
timeRemaining.setText(ststring);
timeRemaining.setTypeface(tf);
}
//--------------------------------------------------------------------------------------------------
public void onClick(View v) {
if(v==abbtn){
aboutFragDialog();
}else if(v==exbtn){
finish();
}else if(v==starest){
if(mTaskFragment.isRunning()){
mTaskFragment.cancel();
} else {
mTaskFragment.start();
}if(v==mgextbtn){
mgcusd.dismiss();
}
}
}
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
public void aboutFragDialog(){
AboutDialog abtdialog = new AboutDialog();
abtdialog.show(getFragmentManager(),"");
}
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
public void addFragDialog(){
AddDialog dialog = new AddDialog();
dialog.minListener = MainActivity.this;
dialog.secListener = MainActivity.this;
dialog.tagListener = MainActivity.this;
dialog.chkbxListener = MainActivity.this;
dialog.show(getFragmentManager(),"");
}
//--------------------------------------------------------------------------------------------------
public void workOutResults(){
val3 = (val1*60)*1000;
val4 = val2*1000;
setTimer((val3+val4)/1000);
temp1 = startTime;
temp2 = String.valueOf(temp1);
starest.setEnabled(true);
if(tagval1.isEmpty()){
savechkbx=false;
}
if(savechkbx){
TimerDataBaseHandler tdb = new TimerDataBaseHandler(getApplicationContext());
tdb.addTimer(new TimerClass(tagval1, temp2));
}
LoadSpinnerData();
}
//--------------------------------------------------------------------------------------------------
public void updateFragDialog(){
TimerDataBaseHandler db = new TimerDataBaseHandler(getApplicationContext());
UpdateDialog updialog = new UpdateDialog();
updialog.uptgListener = MainActivity.this;
updialog.uptimListener = MainActivity.this;
updialog.upposListener = MainActivity.this;
updialog.show(getFragmentManager(),"");
}
//--------------------------------------------------------------------------------------------------
public void updateTimerresults(){
TimerDataBaseHandler mgdb = new TimerDataBaseHandler(getApplicationContext());
SQLiteDatabase mgdb1 = mgdb.getReadableDatabase();
if(mgdb1!=null){
Cursor mgc = mgdb1.rawQuery("SELECT * FROM timers where _id = "+ upposval, null);
if(mgc.moveToFirst()){
mgdb.updateTimer(new TimerClass(upposval, uptagval, uptimeval));
}
}
mgLoadSpinnerData();
}
//--------------------------------------------------------------------------------------------------
public void deleteaTimer(){
TimerDataBaseHandler deldb = new TimerDataBaseHandler(getApplicationContext());
SQLiteDatabase deldb2 = deldb.getReadableDatabase();
int tagposition1 = s.getSelectedItemPosition()+1;
String tagposval = String.valueOf(tagposition1);
if (deldb2 != null) {
Cursor cccc = deldb2.rawQuery("SELECT * FROM timers where _id = " + tagposval, null);
if(cccc.moveToFirst()){
int val0 = cccc.getInt(0);
String val1= cccc.getString(1);
String val2 = cccc.getString(2);
deldb.deleteTimer(new TimerClass(val0, val1, val2));
}
}
LoadSpinnerData();
}
//--------------------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------------------
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
switch(parent.getId()){
case R.id.timerspinner:
TimerDataBaseHandler isdb = new TimerDataBaseHandler(getApplicationContext());
SQLiteDatabase dbsec = isdb.getReadableDatabase();
int tagposition = s.getSelectedItemPosition()+1;
isdb.getReadableDatabase();
Cursor cc = dbsec.rawQuery("SELECT * FROM timers WHERE _id = "+tagposition, null);
if(cc.moveToFirst()){
setTimer(Integer.parseInt(cc.getString(2)));
starest.setEnabled(true);
replaceFrag();
}
}
}
//--------------------------------------------------------------------------------------------------
#Override
public void onNothingSelected(AdapterView<?> adapterView) { }
//--------------------------------------------------------------------------------------------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//--------------------------------------------------------------------------------------------------
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_new) {
addFragDialog();
return true;
}else if (id == R.id.action_discard) {
deleteaTimer();
return true;
}else if (id == R.id.action_edit) {
updateFragDialog();
return true;
}
return super.onOptionsItemSelected(item);
}
//--------------------------------------------------------------------------------------------------
public void setOSMinListener(String arg){
val1 = Integer.parseInt(arg);
}
public void setOSSecListener(String arg){
val2 = Integer.parseInt(arg);
}
public void setOSTagListener(String arg){
tagval1 = arg;
}
public void setOSCkbListener(String arg){
savechkbx = Boolean.parseBoolean(arg);
}
public void updateOStagListener(String arg){
uptagval = arg;
}
public void updateOSTimeListener(String arg) {
uptimeval = arg;
}
public void updateOSPosListener(String arg){
upposval = Integer.parseInt(arg);
}
public void replaceFrag(){
Bundle bundle = new Bundle();
String tester2 = String.valueOf(startTime).toString();
Log.i("VertygoEclypse - replaceFrag - Value for counter ", tester2);
if(tester2.matches("")){
bundle.putString("SecValue", "15");
} else {
bundle.putString("SecValue", tester2);
}
FragmentManager rfm = getSupportFragmentManager();
if(mTaskFragment == null){
TaskFragment mTaskFragment = new TaskFragment();
mTaskFragment.setArguments(bundle);
rfm.beginTransaction().add(mTaskFragment, "task").commit();
} else {
TaskFragment mTaskFragment = new TaskFragment();
mTaskFragment = (TaskFragment) rfm.findFragmentByTag("task");
mTaskFragment.setArguments(bundle);
rfm.beginTransaction().add(mTaskFragment, "task").commit();
}
}
public void initialfrag(){
Log.i("VertygoEclypse - InitialFrag ","Called");
Bundle bundl = new Bundle();
String tester = timeRemaining.getText().toString();
if(tester.matches("")){
bundl.putString("SecValue", "15");
} else{
bundl.putString("SecValue", String.valueOf(startTime).toString());
}
FragmentManager fm = getSupportFragmentManager();
TaskFragment mTaskFragment = new TaskFragment();
mTaskFragment = (TaskFragment) fm.findFragmentByTag("task");
if (mTaskFragment == null) {
mTaskFragment = new TaskFragment();
mTaskFragment.setArguments(bundl);
fm.beginTransaction().add(mTaskFragment, "task").commit();
}
}
#Override
public void onPreExecute() {
starest.setText("cancel");
}
#Override
public void onProgressUpdate(int timer) {
setTimer(timer);
}
#Override
public void onCancelled() {
starest.setText("Start");
timeRemaining.setTypeface(tf);
timeRemaining.setText("0 seconds");
mTaskFragment.cancel();
replaceFrag();
}
#Override
public void onPostExecute() {
starest.setText("Start");
timeRemaining.setTypeface(tf);
timeRemaining.setText("Completed");
mTaskFragment.cancel();
replaceFrag();
}
}
Any help on this would be appreciated.
regards
cchinchoy
Once more it would seem that I have answered my own question, with 2 solid days of trial and error on the code, I actually got the idea from another question I posted. The mRunning value needed to be static so that it would be the same for the tasks across the Activity and the Fragment. That being the case changing the code as private boolean mRunning; to this private static boolean mRunning; allow the code to now fire as it is supposed to. Being new to android programming, I am still getting accustomed to the need for the qualifiers such as public, private, static and the sorts. I hope this will help other newbies like myself and help to save the days of pouring over the code to try and find the issue.
thanks once again for the sounding board.
regards
cchinchoy
This is the code of my main page:
package com.buanasoft.toko;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class f_penjualan extends Activity {
private long rowID;
private TextView nm_barangTv;
private TextView hargaTv;
private TextView h_jualTv;
private TextView satuanTv;
private TextView stokTv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.f_penjualan);
setUpViews();
Bundle extras = getIntent().getExtras();
rowID = extras.getLong(f_data.ROW_ID);
Button go = (Button)findViewById(R.id.btn_pilih);
Intent i = this.getIntent();
go.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(getApplicationContext(), daftar_barang.class);
startActivity(i);
}
});
}
private void setUpViews() {
nm_barangTv = (TextView) findViewById(R.id.namaBarangText);
hargaTv = (TextView) findViewById(R.id.hargaBarangText);
h_jualTv = (TextView) findViewById(R.id.hargaJualText);
satuanTv = (TextView) findViewById(R.id.satuanText);
stokTv = (TextView) findViewById(R.id.stokText);
}
#Override
protected void onResume()
{
super.onResume();
new LoadBarang().execute(rowID);
}
private class LoadBarang extends AsyncTask<Long, Object, Cursor>
{
DBCon_barang dbCon_barang = new DBCon_barang(f_penjualan.this);
#Override
protected Cursor doInBackground(Long... params)
{
dbCon_barang.open();
return dbCon_barang.getOneBarang(params[0]);
}
#Override
protected void onPostExecute(Cursor result)
{
super.onPostExecute(result);
result.moveToFirst();
// get the column index for each data item
int nm_barangIndex = result.getColumnIndex("nm_barang");
int hargaIndex = result.getColumnIndex("harga");
int h_jualIndex = result.getColumnIndex("h_jual");
int satuanIndex = result.getColumnIndex("satuan");
int stokIndex = result.getColumnIndex("stok");
nm_barangTv.setText(result.getString(nm_barangIndex));
hargaTv.setText(result.getString(hargaIndex));
h_jualTv.setText(result.getString(h_jualIndex));
satuanTv.setText(result.getString(satuanIndex));
stokTv.setText(result.getString(stokIndex));
result.close();
dbCon_barang.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.det_data_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.editItem:
Intent addEditBarang =
new Intent(this, AddEditBarang.class);
addEditBarang.putExtra(f_data.ROW_ID, rowID);
addEditBarang.putExtra("nm_barang", nm_barangTv.getText());
addEditBarang.putExtra("harga", hargaTv.getText());
addEditBarang.putExtra("h_jual", h_jualTv.getText());
addEditBarang.putExtra("satuan", satuanTv.getText());
addEditBarang.putExtra("stok", stokTv.getText());
startActivity(addEditBarang);
return true;
case R.id.deleteItem:
deleteBarang();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void deleteBarang()
{
AlertDialog.Builder alert = new AlertDialog.Builder(f_penjualan.this);
alert.setTitle(R.string.confirmTitle);
alert.setMessage(R.string.confirmMessage);
alert.setPositiveButton(R.string.delete_btn,
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int button)
{
final DBCon_barang dbCon_barang =
new DBCon_barang (f_penjualan.this);
AsyncTask<Long, Object, Object> deleteTask =
new AsyncTask<Long, Object, Object>()
{
#Override
protected Object doInBackground(Long... params)
{
dbCon_barang.deleteBarang(params[0]);
return null;
}
#Override
protected void onPostExecute(Object result)
{
finish();
}
};
deleteTask.execute(new Long[] { rowID });
}
}
);
alert.setNegativeButton(R.string.cancel_btn, null).show();
}
}
and this is the code from my second activity
public class daftar_barang extends ListActivity {
public static final String ROW_ID = "row_id";
private ListView conListView;
private CursorAdapter conAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
////script untuk memampilkan daftar barang & menu
conListView=getListView();
conListView.setOnItemClickListener(viewConListener);
// mengisi value di TextView
String[] from = new String[] { "nm_barang" };
int[] to = new int[] { R.id.daftar_barang };
conAdapter = new SimpleCursorAdapter(daftar_barang.this, R.layout.daftar_barang, null, from, to);
setListAdapter(conAdapter); // set adapter
}
#Override
protected void onResume()
{
super.onResume();
new GetData().execute((Object[]) null);
}
#Override
protected void onStop()
{
Cursor cursor = conAdapter.getCursor();
if (cursor != null)
cursor.deactivate();
conAdapter.changeCursor(null);
super.onStop();
}
private class GetData extends AsyncTask<Object, Object, Cursor>
{
DBCon_barang dbConnector = new DBCon_barang(daftar_barang.this);
#Override
protected Cursor doInBackground(Object... params)
{
dbConnector.open();
return dbConnector.getAllBarang();
}
#Override
protected void onPostExecute(Cursor result)
{
conAdapter.changeCursor(result); // set the adapter's Cursor
dbConnector.close();
}
}
//fungsi untuk melihat detail barang
OnItemClickListener viewConListener = new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
{
Intent viewCon = new Intent(daftar_barang.this,f_penjualan.class);
viewCon.putExtra(ROW_ID, arg3);
startActivity(viewCon);
}
};
}
I want to display the data item from my second activity to first activity.
So by the time I get into the second activity and I click on one of the data in the second activity, he will be on show to the first activity.
There is no error warning, but after building my application some errors occurred when I open the activity.
Your problem is in onCreate() of the first activity. You have this code:
Bundle extras = getIntent().getExtras();
rowID = extras.getLong(f_data.ROW_ID);
When your activity is first launched it won't contain any extras, so the call to getIntent().getExtras() will return null. The next statement will then throw a NullPointerException. You need to check for extras == null before calling getLong() on it.