My text view disappear in list view while scrolling - java

I have a list of musics, so I want user to set time to play music in particular time.
here I have a list view that has a text view (is invisible at first) and a button.
when I click on the button an alert dialog open to show device time and a time picker.
I subtract these times and sent the result to the Count Down Timer, In on Tick
i set my text view visible to show time to user until to finish the time.
all things are correct
user can play music after the time which sets.
but when I scroll the list view ,my text view (show the timer )disappeared.
here is my code:
public class Main extends Activity {
public static int hour_device, minute_device;
public static int hour_user, minute_user;
Splash splash;
ListView listView;
Adaptor adaptor;
private MediaPlayer mediaPlayer;
static View lastview = null;
static MyIndexStore indexStore;
List<String> lines1 = new ArrayList<String>();
List<String> lines2 = new ArrayList<String>();
static List<String> array_audio = new ArrayList<String>();
InputStream in;
BufferedReader reader;
String line = "1";
String[] tracks;
String[] names;
String[] infos;
HashMap<Integer,String> textMap;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
indexStore = new MyIndexStore(getApplicationContext());
setContentView(R.layout.main_activity);
splash = new Splash(this);
splash.set_identity("1");
initiate();
mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.a1);
//lastview = null;
listView = (ListView) findViewById(R.id.list);
ReadText1();
names = lines1.toArray(new String[0]);// = {"track one","the seconnd track","a nice track","name name name","the seconnd track","a nice track","name name name"};
ReadText2();
infos = lines2.toArray(new String[0]);
tracks = array_audio.toArray(new String[0]);
adaptor = new Adaptor(getApplicationContext(), tracks, names, infos,textMap);
listView.setAdapter(adaptor);
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
if (lastview != null) {
ImageView play = (ImageView) lastview.findViewById(R.id.play_stop);
play.setImageResource(R.drawable.n_btn_play_unselected);
}
}
});
}
private static void initiate() {
Field[] fields = R.raw.class.getFields();
array_audio.clear();
for (int count = 0; count < fields.length; count++) {
array_audio.add("a" + (count + 1));
}
}
private void play(int index) {
mediaPlayer.release();
index++;
String s = "a" + index;
Resources resources = getResources();
final int resourceId = resources.getIdentifier(s, "raw", getPackageName());
try {
mediaPlayer = MediaPlayer.create(this, resourceId);
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onPause() {
mediaPlayer.release();
listView.invalidateViews();
super.onPause();
}
private void ReadText1() {
lines1.clear();
line = "1";
try {
in = this.getAssets().open("names.txt");
reader = new BufferedReader(new InputStreamReader(in));
while (line != null) {
line = reader.readLine();
if (line != null)
lines1.add(line);
else
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void ReadText2() {
lines2.clear();
line = "1";
try {
in = this.getAssets().open("infos.txt");
reader = new BufferedReader(new InputStreamReader(in));
while (line != null) {
line = reader.readLine();
if (line != null)
lines2.add(line);
else
break;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public class Adaptor extends ArrayAdapter<String> {
private final Context context;
private final String[] tracks;
private final String[] names;
private final String[] infos;
private final HashMap<Integer,String> textMap;
Typeface type_face;
public Adaptor(Context context, String[] tracks, String[] names, String[] infos,HashMap<Integer,String> textMap) {
super(context, R.layout.track, tracks);
this.context = context;
this.tracks = tracks;
this.names = names;
this.infos = infos;
type_face = Typeface.createFromAsset(context.getAssets(), "BTitrBd.ttf");
this.textMap = textMap;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView = inflater.inflate(R.layout.track, parent, false);
TextView name = (TextView) rowView.findViewById(R.id.track_name);
final TextView time = (TextView) rowView.findViewById(R.id.time);
//populate the textview from map
if(textMap!=null && textMap.get(new Integer(position))!=null){
time.setText(textMap.get(new Integer(position)));
}
name.setText(names[position]);
name.setTypeface(type_face);
name.setTypeface(type_face);
final ImageView ringtone = (ImageView) rowView.findViewById(R.id.ringtone);
if (position == indexStore.getindex())
ringtone.setImageResource(R.drawable.n_btn_ringtone_seted);
final ImageView play = (ImageView) rowView.findViewById(R.id.play_stop);
ringtone.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
LayoutInflater factory = LayoutInflater.from(Main.this);
final View deleteDialogView = factory.inflate(
R.layout.mylayout, null);
final AlertDialog deleteDialog = new AlertDialog.Builder(Main.this).create();
deleteDialog.setView(deleteDialogView);
TextView device_time = (TextView) deleteDialogView.findViewById(R.id.current_time);
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
hour_device = hour;
minute_device = minute;
device_time.setText(hour_device + ":" + minute_device);
deleteDialogView.findViewById(R.id.set).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TimePicker timePicker = (TimePicker) deleteDialogView.findViewById(R.id.timepicker);
timePicker.setIs24HourView(true);
hour_user = timePicker.getCurrentHour();
minute_user = timePicker.getCurrentMinute();
String time1 = hour_device + ":" + minute_device;
String time2 = hour_user + ":" + minute_user;
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
Date date1 = null;
try {
date1 = format.parse(time1);
} catch (ParseException e) {
e.printStackTrace();
}
Date date2 = null;
try {
date2 = format.parse(time2);
} catch (ParseException e) {
e.printStackTrace();
}
long result = date2.getTime() - date1.getTime();
new CountDownTimer(result, 1000) {
public void onTick(long millisUntilFinished) {
time.setText(("seconds remaining: " + millisUntilFinished / 1000));
//create HashMap<Integer,String> textMap at the constructer of the adapter
//now fill this info into it
textMap.put(new Integer(position),"seconds remaining: " + millisUntilFinished / 1000);
//notify about the data change
notifyDataSetChanged();
}
public void onFinish() {
time.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(), "finish", Toast.LENGTH_LONG).show();
if (rowView != lastview || mediaPlayer == null) {
play(position);
if (lastview != null)
lastview = rowView;
} else {
play.setImageResource(R.drawable.n_btn_play_unselected);
mediaPlayer.release();
lastview = null;
}
}
}.start();
deleteDialog.dismiss();
}
});
deleteDialog.show();
}
});
play.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (rowView != lastview || mediaPlayer == null) {
play(position);
if (lastview != null)
lastview = rowView;
} else {
play.setImageResource(R.drawable.n_btn_play_unselected);
mediaPlayer.release();
lastview = null;
}
}
});
return rowView;
}
}
}
I need help, any suggestion?
I'm new with android:-)

Update your countdown timer like this
new CountDownTimer(result, 1000) {
public void onTick(long millisUntilFinished) {
time.setText(("seconds remaining: " + millisUntilFinished / 1000));
//create HashMap<Integer,String> textMap at the constructer of the adapter
//whenever you want to clear a record clear the hash map
//now fill this info into it
textMap.put(new Integer(position),"seconds remaining: " + millisUntilFinished / 1000);
//notify about the data change
notifyDataSetChanged();
}
public void onFinish() {
time.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(), "finish", Toast.LENGTH_LONG).show();
if (rowView != lastview || mediaPlayer == null) {
play(position);
if (lastview != null)
lastview = rowView;
} else {
play.setImageResource(R.drawable.n_btn_play_unselected);
mediaPlayer.release();
lastview = null;
}
}
}.start();
At the place where you initiate the textView text;
final TextView time = (TextView) rowView.findViewById(R.id.time);
//populate the textview from map
if(textMap!=null && textMap.get(new Integer(position))!=null){
time.setText(textMap.get(new Integer(position)));
}
This continuous update might cause lag issues.

You must use Reclyclerview for this, textview is primitive for your requirement.
https://developer.android.com/training/material/lists-cards.html

Related

my app is crashing when there is no internet and i want my markers or my map to refresh each second

i made a googlemap app where my markers are displyed.
the problem is when there no internet, the app is crashing. The code under onResume does not solve the problem.
also i want to refresh the map or markers each second on the map.
if you have any ideas please i am here to learn from all of you.
here is my MapActivity code :
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback
{
private static final String TAG = "MapActivity";
#Bind(R.id.back)
View back;
#Bind(R.id.zoom_in)
View zoom_in;
#Bind(R.id.zoom_out)
View zoom_out;
#Bind(R.id.updatetimer)
TextView updatetimer;
#Bind(R.id.autozoom)
ImageView autozoom;
#Bind(R.id.showtails)
ImageView showtails;
#Bind(R.id.geofences)
ImageView showGeofences;
#Bind(R.id.map_layer)
ImageView map_layer_icon;
private GoogleMap map;
#Bind(R.id.content_layout)
View content_layout;
#Bind(R.id.loading_layout)
View loading_layout;
#Bind(R.id.nodata_layout)
View nodata_layout;
private Timer timer;
private int autoZoomedTimes = 0;// dėl bugo osmdroid library, zoom'inam du kartus ir paskui po refresh'o nebe, nes greičiausiai user'is bus pakeitęs zoom'ą
private HashMap<Integer, Marker> deviceIdMarkers;
private HashMap<String, Device> markerIdDevices;
private HashMap<Integer, Polyline> deviceIdPolyline;
private HashMap<Integer, LatLng> deviceIdLastLatLng;
// private HashMap<Integer, Marker> deviceIdSmallMarkerInfo;
private long lastRefreshTime;
boolean isAutoZoomEnabled = true;
boolean isShowTitlesEnabled;
boolean isShowTailsEnabled = true;
boolean isShowGeofencesEnabled = true;
private String stopTime;
private AsyncTask downloadingAsync;
private boolean isRefreshLoced = false;
ApiInterface.GetGeofencesResult geofencesResult;
ArrayList<PolygonWithName> polygonsWithDetails = new ArrayList<>();
float previousZoomLevel = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
ButterKnife.bind(this);
deviceIdMarkers = new HashMap<>();
markerIdDevices = new HashMap<>();
deviceIdPolyline = new HashMap<>();
deviceIdLastLatLng = new HashMap<>();
// deviceIdSmallMarkerInfo = new HashMap<>();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
protected void onResume()
{
super.onResume();
timer = new Timer();
timer.schedule(new TimerTask()
{
#Override
public void run()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
float timeleft = 10 - Math.round(System.currentTimeMillis() - lastRefreshTime) / 1000f;
if (timeleft < 0)
timeleft = 0;
updatetimer.setText(String.format("%.0f", timeleft));
if (System.currentTimeMillis() - lastRefreshTime >= 10 * 1000)
if (map != null)
refresh();
}
});
}
}, 0, 1000);
}
#Override
protected void onPause()
{
super.onPause();
try
{
timer.cancel();
timer.purge();
downloadingAsync.cancel(true);
} catch (Exception e)
{
e.printStackTrace();
}
}
private void refresh()
{
if (isRefreshLoced)
return;
isRefreshLoced = true;
lastRefreshTime = System.currentTimeMillis();
final String api_key = (String) DataSaver.getInstance(this).load("api_key");
API.getApiInterface(this).getDevices(api_key, getResources().getString(R.string.lang), new Callback<ArrayList<ApiInterface.GetDevicesItem>>()
{
#Override
public void success(final ArrayList<ApiInterface.GetDevicesItem> getDevicesItems, Response response)
{
Log.d(TAG, "success: loaded devices array");
final ArrayList<Device> allDevices = new ArrayList<>();
if (getDevicesItems != null)
for (ApiInterface.GetDevicesItem item : getDevicesItems)
allDevices.addAll(item.items);
API.getApiInterface(MapActivity.this).getFieldsDataForEditing(api_key, getResources().getString(R.string.lang), 1, new Callback<ApiInterface.GetFieldsDataForEditingResult>()
{
#Override
public void success(final ApiInterface.GetFieldsDataForEditingResult getFieldsDataForEditingResult, Response response)
{
Log.d(TAG, "success: loaded icons");
downloadingAsync = new AsyncTask<Void, Void, Void>()
{
ArrayList<MarkerOptions> markers;
ArrayList<Integer> deviceIds;
#Override
protected Void doInBackground(Void... params)
{
// add markers
int dp100 = Utils.dpToPx(MapActivity.this, 50);
markers = new ArrayList<>();
deviceIds = new ArrayList<>();
if (getFieldsDataForEditingResult == null || getFieldsDataForEditingResult.device_icons == null)
return null;
for (Device item : allDevices)
{
if (isCancelled())
break;
if (item.device_data.active == 1)
{
// ieškom ikonos masyve
DeviceIcon mapIcon = null;
for (DeviceIcon icon : getFieldsDataForEditingResult.device_icons)
if (item.device_data.icon_id == icon.id)
mapIcon = icon;
String server_base = (String) DataSaver.getInstance(MapActivity.this).load("server_base");
try
{
Log.d("MapActivity", "DOWNLOADING BITMAP: " + server_base + mapIcon.path);
Bitmap bmp = BitmapFactory.decodeStream(new URL(server_base + mapIcon.path).openConnection().getInputStream());
int srcWidth = bmp.getWidth();
int srcHeight = bmp.getHeight();
int maxWidth = Utils.dpToPx(MapActivity.this, mapIcon.width);
int maxHeight = Utils.dpToPx(MapActivity.this, mapIcon.height);
float ratio = Math.min((float) maxWidth / (float) srcWidth, (float) maxHeight / (float) srcHeight);
int dstWidth = (int) (srcWidth * ratio);
int dstHeight = (int) (srcHeight * ratio);
bmp = bmp.createScaledBitmap(bmp, dp100, dp100, true);
// marker
MarkerOptions m = new MarkerOptions();
m.position(new LatLng(item.lat, item.lng));
// marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM);
// marker.setIcon(new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bmp, dstWidth, dstHeight, true)));
m.icon(BitmapDescriptorFactory.fromBitmap(Bitmap.createScaledBitmap(bmp, dstWidth, dstHeight, true)));
// info window
// MapMarkerInfoWindow infoWindow = new MapMarkerInfoWindow(MapActivity.this, item, R.layout.layout_map_infowindow, map);
// marker.setInfoWindow(infoWindow);
markers.add(m);
deviceIds.add(item.id);
} catch (OutOfMemoryError outOfMemoryError)
{
Toast.makeText(MapActivity.this, "Out of memory! Too many devices are selected to be displayed", Toast.LENGTH_LONG).show();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid)
{
ArrayList<GeoPoint> points = new ArrayList<>();
if (autoZoomedTimes < 1)
{
new Handler().postDelayed(new Runnable()
{
#Override
public void run()
{
runOnUiThread(new Runnable()
{
#Override
public void run()
{
if (markers.size() > 1)
{
try
{
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (MarkerOptions item : markers)
builder.include(item.getPosition());
LatLngBounds bounds = builder.build();
// int padding = 0; // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, Utils.dpToPx(MapActivity.this, 50));
map.animateCamera(cu);
} catch (Exception e)
{
}
} else if (markers.size() > 0)
{
map.moveCamera(CameraUpdateFactory.newLatLngZoom(markers.get(0).getPosition(), 15));
}
autoZoomedTimes++;
}
});
}
}, 50);
} else if (isAutoZoomEnabled)
{
if (markers.size() > 1)
{
try
{
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (MarkerOptions item : markers)
builder.include(item.getPosition());
LatLngBounds bounds = builder.build();
// int padding = 0; // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, Utils.dpToPx(MapActivity.this, 50));
map.animateCamera(cu);
} catch (Exception e)
{
}
} else if (markers.size() > 0)
{
map.moveCamera(CameraUpdateFactory.newLatLngZoom(markers.get(0).getPosition(), 15));
}
autoZoomedTimes++;
}
Log.d(TAG, "onPostExecute: icons downloaded and added to map, total markers: " + markers.size());
loading_layout.setVisibility(View.GONE);
if (markers.size() != 0)
content_layout.setVisibility(View.VISIBLE);
else
nodata_layout.setVisibility(View.VISIBLE);
for (int i = 0; i < markers.size(); i++)
{
MarkerOptions options = markers.get(i);
int deviceId = deviceIds.get(i);
Marker m;
Polyline polyline;
if (deviceIdMarkers.containsKey(deviceId))
{
Log.d("aa", "moving to" + options.getPosition());
deviceIdMarkers.get(deviceId).setPosition(new LatLng(options.getPosition().latitude, options.getPosition().longitude));
m = deviceIdMarkers.get(deviceId);
polyline = deviceIdPolyline.get(deviceId);
} else
{
Log.d("aa", "putting new");
m = map.addMarker(options);
deviceIdMarkers.put(deviceId, m);
polyline = map.addPolyline(new PolylineOptions());
deviceIdPolyline.put(deviceId, polyline);
}
Device thatonedevice = null;
for (Device device : allDevices)
if (device.id == deviceId)
thatonedevice = device;
markerIdDevices.put(m.getId(), thatonedevice);
// update marker rotation based on driving direction
if (thatonedevice != null && deviceIdLastLatLng.containsKey(deviceId))
{
double dirLat = thatonedevice.lat - deviceIdLastLatLng.get(deviceId).latitude;
double dirLng = thatonedevice.lng - deviceIdLastLatLng.get(deviceId).longitude;
m.setRotation((float) Math.toDegrees(Math.atan2(dirLng, dirLat)));
}
deviceIdLastLatLng.put(deviceId, new LatLng(thatonedevice.lat, thatonedevice.lng));
List<LatLng> polylinePoints = new ArrayList<>();
for (TailItem item : thatonedevice.tail)
polylinePoints.add(new LatLng(Double.valueOf(item.lat), Double.valueOf(item.lng)));
polyline.setPoints(polylinePoints);
polyline.setWidth(Utils.dpToPx(MapActivity.this, 2));
polyline.setColor(Color.parseColor(thatonedevice.device_data.tail_color));
}
// else
map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter()
{
#Override
public View getInfoWindow(Marker marker)
{
return null;
}
#Override
public View getInfoContents(final Marker marker)
{
synchronized (this)
{
}
final Device device = markerIdDevices.get(marker.getId());
if (device != null)
{
View view = getLayoutInflater().inflate(R.layout.layout_map_infowindow, null);
view.bringToFront();
view.findViewById(R.id.close).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
marker.hideInfoWindow();
}
});
TextView device_name = (TextView) view.findViewById(R.id.device_name);
device_name.setText(device.name);
TextView altitude = (TextView) view.findViewById(R.id.altitude);
altitude.setText(String.valueOf(device.altitude) + " " + device.unit_of_altitude);
TextView time = (TextView) view.findViewById(R.id.time);
time.setText(device.time);
TextView stopTimeView = (TextView) view.findViewById(R.id.stopTime);
stopTimeView.setText(stopTime);
TextView speed = (TextView) view.findViewById(R.id.speed);
speed.setText(device.speed + " " + device.distance_unit_hour);
TextView address = (TextView) view.findViewById(R.id.address);
address.setText(device.address);
final ArrayList<Sensor> showableSensors = new ArrayList<>();
for (Sensor item : device.sensors)
if (item.show_in_popup > 0)
showableSensors.add(item);
ListView sensors_list = (ListView) view.findViewById(R.id.sensors_list);
sensors_list.setAdapter(new AwesomeAdapter<Sensor>(MapActivity.this)
{
#Override
public int getCount()
{
return showableSensors.size();
}
#NonNull
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent)
{
if (convertView == null)
convertView = getLayoutInflater().inflate(R.layout.adapter_map_sensorslist, null);
Sensor item = showableSensors.get(position);
TextView name = (TextView) convertView.findViewById(R.id.name);
name.setText(item.name);
TextView value = (TextView) convertView.findViewById(R.id.value);
value.setText(item.value);
return convertView;
}
});
List<Address> addresses;
try
{
addresses = new Geocoder(MapActivity.this).getFromLocation(device.lat, device.lng, 1);
if (addresses.size() > 0)
address.setText(addresses.get(0).getAddressLine(0));
} catch (IOException e)
{
e.printStackTrace();
}
return view;
}
return null;
}
});
map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener()
{
#Override
public boolean onMarkerClick(final Marker marker)
{
int px = Utils.dpToPx(MapActivity.this, 300);
map.setPadding(0, px, 0, 0);
stopTime = "...";
final Device device = markerIdDevices.get(marker.getId());
if (device != null)
{
API.getApiInterface(MapActivity.this).deviceStopTime((String) DataSaver.getInstance(MapActivity.this).load("api_key"), "en", device.id, new Callback<ApiInterface.DeviceStopTimeResult>()
{
#Override
public void success(ApiInterface.DeviceStopTimeResult result, Response response)
{
stopTime = result.time;
marker.showInfoWindow();
}
#Override
public void failure(RetrofitError retrofitError)
{
Toast.makeText(MapActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
}
});
}
return false;
}
});
map.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener()
{
#Override
public void onInfoWindowClick(Marker marker)
{
marker.hideInfoWindow();
}
});
map.setOnInfoWindowCloseListener(new GoogleMap.OnInfoWindowCloseListener()
{
#Override
public void onInfoWindowClose(Marker marker)
{
map.setPadding(0, 0, 0, 0);
}
});
// updateSmallMarkerData(allDevices);
isRefreshLoced = false;
}
}.execute();
}
#Override
public void failure(RetrofitError retrofitError)
{
Toast.makeText(MapActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
isRefreshLoced = false;
}
});
}
#Override
public void failure(RetrofitError retrofitError)
{
Toast.makeText(MapActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
isRefreshLoced = false;
}
});
}
#Override
public void onMapReady(GoogleMap googleMap)
{
map = googleMap;
refresh();
}
this MapActivity is slow to load, could you teach me a way to make it goes faster?
Best regard :)
waiting for your propositions.
PS: i have removed some functions to make the code look short but i kept the most important in is case.
For the crashing issue
create a class
public class NetWorkChecker {
static NetworkInfo wifi, mobile;
public static Boolean check(Context c) {
ConnectivityManager cm = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
try {
wifi = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
mobile = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
} catch (Exception e) {
e.printStackTrace();
}
if (wifi != null && wifi.isConnected() && wifi.isAvailable()) {
return true;
} else if (mobile != null && mobile.isAvailable() && mobile.isConnected()) {
return true;
} else {
//Toast.makeText(c, "No Network Connection", Toast.LENGTH_SHORT).show();
// ((Activity) c).finish();
displayMobileDataSettingsDialog(c,"No Network Connection","No Network Connection");
return false;
}
}
public static AlertDialog displayMobileDataSettingsDialog(final Context context, String title, String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle(title);
builder.setMessage(message);
builder.setCancelable(false);
builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
context.startActivity(intent);
}
});
builder.show();
return builder.create();
}
}
to check if the devise have an active internet connection
call
if (!NetWorkChecker.check(this)){
////do your refres
}

save state of my game in database

In my project I download all the data of my project from a json.I download title and description as text and also download my icon and the file of games.
I can download them and also save in database and show in listview easily.
My QUESTION is about how to save that my file for game is beinng download or not?
I have two buttons. first is download button when user click it , it starts to download file.when download finish, my download button disappear and my play button appears.
I want to save this, when user for second time run the application,i save for example my second position downloaded before. and I have just my play button.
my database:
public class DatabaseHandler extends SQLiteOpenHelper {
public SQLiteDatabase sqLiteDatabase;
int tedad;
public DatabaseHandler(Context context) {
super(context, "EmployeeDatabase.db", null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String tableEmp = "create table emp(PersianTitle text,Description text,icon text,downloadlink text,dl integer)";
db.execSQL(tableEmp);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void insertData(ArrayList<String> id, ArrayList<String> name, ArrayList<String> salary, ArrayList<String> roms,String
dl) {
int size = id.size();
tedad = size;
sqLiteDatabase = this.getWritableDatabase();
try {
for (int i = 0; i < size; i++) {
ContentValues values = new ContentValues();
values.put("PersianTitle", id.get(i));
values.put("Description", name.get(i));
values.put("icon", salary.get(i));
values.put("downloadlink", roms.get(i));
values.put("dl", "0");
sqLiteDatabase.insert("emp", null, values);
}
} catch (Exception e) {
Log.e("Problem", e + " ");
}
}
public ArrayList<String> Game_Info (int row, int field) {
String fetchdata = "select * from emp";
SQLiteDatabase sqLiteDatabase = this.getReadableDatabase();
ArrayList<String> stringArrayList = new ArrayList<String>();
Cursor cu = sqLiteDatabase.rawQuery(fetchdata, null);
for (int i = 0; i < row + 1; i++) {
cu.moveToPosition(i);
String s = cu.getString(field);
stringArrayList.add(s);
}
return stringArrayList;
}
}
and this is my main code:
public class MainActivity2 extends Activity {
Boolean done_game = false;
ProgressDialog progressDialog;
private boolean _init = false;
ListView listView;
DatabaseHandler database;
BaseAdapter adapter;
public String path_image;
JSONObject jsonObject;
Game_Counter_Store Game_Counter_Store;
int game_counter_store;
ArrayList<String> name_array = new ArrayList<String>();
ArrayList<String> des_array = new ArrayList<String>();
ArrayList<String> icon_array = new ArrayList<String>();
ArrayList<String> roms_array = new ArrayList<String>();
ArrayList<String> fav_array = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main2);
init();
System.gc();
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), "MyDirName");//make a direction
path_image = mediaStorageDir.getAbsolutePath(); // here is tha path
listView = (ListView) findViewById(R.id.listView);
database = new DatabaseHandler(MainActivity2.this);
database.getWritableDatabase();
Game_Counter_Store = new Game_Counter_Store("Games_Number", this); // number of game in first run is 0
game_counter_store = Game_Counter_Store.get_count();
if (game_counter_store == 0) {
Log.i("mhs", "game_counter_store is 0");
DownloadGames();
} else {
Log.i("mhs", "there are some games");
for (int i = 0; i < game_counter_store; i++) {
name_array = database.Game_Info(i, 0);
des_array = database.Game_Info(i, 1);
icon_array = database.Game_Info(i, 2);
roms_array = database.Game_Info(i, 3);
fav_array = database.Game_Info(i, 4);
}
adapter = new MyBaseAdapter(MainActivity2.this, name_array, des_array, icon_array, roms_array,fav_array);
listView.setAdapter(adapter);
}
}
public void DownloadGames() {
//here we download name, des, icon
MakeDocCallBack makeDocCallBack = new MakeDocCallBack() {
#Override
public void onResult(ArrayList<String> res) {
if (res.size() > 0) {
try {
Game_Counter_Store counter_store = new Game_Counter_Store("Games_Number", MainActivity2.this); // get numbrr of games
counter_store.set_count(res.size()); // store the games number
for (int i = 0; i < res.size(); i++) {
jsonObject = new JSONObject(res.get(i)); //get all the jsons
//get all the data to store in database
name_array.add(jsonObject.getString("PersianTitle"));
des_array.add(jsonObject.getString("Description"));
icon_array.add(jsonObject.getString("icon"));
roms_array.add(jsonObject.getString("downloadlink"));
GetFile fd = new GetFile(MainActivity2.this, path_image, getFileName(jsonObject.getString("icon")), jsonObject.getString("icon").toString(), null); // download the image
GetFileCallBack Image_callback = new GetFileCallBack() {
#Override
public void onStart() {
// Toast.makeText(getApplicationContext(),"start",Toast.LENGTH_LONG).show();
}
#Override
public void onProgress(long l, long l1) {
// Toast.makeText(getApplicationContext(),"onProgress",Toast.LENGTH_LONG).show();
}
#Override
public void onSuccess() {
// Toast.makeText(getApplicationContext(),"YES",Toast.LENGTH_LONG).show();
}
#Override
public void onFailure() {
// Toast.makeText(getApplicationContext(),"NO",Toast.LENGTH_LONG).show();
}
};
if (!fd.DoesFileExist()) {
fd.Start(Image_callback); // get the data
}
//set data in adapter to show in listview
adapter = new MyBaseAdapter(MainActivity2.this, name_array, des_array, icon_array, roms_array,fav_array);
listView.setAdapter(adapter);
}
//store dada in database (name , des , icon , bin file(roms) , state)
database.insertData(name_array, des_array, icon_array, roms_array,"0");
} catch (Exception ex) {
}
}
}
};
DocMaker doc = new DocMaker();
doc.set(this, makeDocCallBack);
}
public static String getFileName(String url) {
String temp = url.substring(url.lastIndexOf('/') + 1, url.length());
if (temp.contains("?"))
temp = temp.substring(0, temp.indexOf("?"));
return temp;
}
public class MyBaseAdapter extends BaseAdapter {
private Activity activity;
private ArrayList title, desc, icon, roms,fav;
private LayoutInflater inflater = null;
public MyBaseAdapter(Activity a, ArrayList b, ArrayList c, ArrayList d, ArrayList e, ArrayList f) {
activity = a;
this.title = b;
this.desc = c;
this.icon = d;
this.roms = e;
this.fav=f;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return title.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.list_item, null);
TextView title2 = (TextView) vi.findViewById(R.id.game_name); // title
String song = title.get(position).toString();
title2.setText(song);
TextView title22 = (TextView) vi.findViewById(R.id.game_des); // desc
String song2 = desc.get(position).toString();
title22.setText(song2);
File imageFile = new File("/storage/emulated/0/MyDirName/" + getFileName(icon_array.get(position)));
ImageView imageView = (ImageView) vi.findViewById(R.id.icon); // icon
imageView.setImageBitmap(BitmapFactory.decodeFile(imageFile.getAbsolutePath()));
TextView title222 = (TextView) vi.findViewById(R.id.game_roms); // desc
String song22 = roms.get(position).toString();
title222.setText(song22);
final Button dl_btn = (Button) vi.findViewById(R.id.dl_btn); // desc
final Button run_btn = (Button) vi.findViewById(R.id.play_btn); // desc
run_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Preferences.DEFAULT_GAME_FILENAME = getFileName(roms_array.get(position));
Intent myIntent = new Intent(MainActivity2.this, FileChooser.class);
myIntent.putExtra(FileChooser.EXTRA_START_DIR, Preferences.getRomDir(MainActivity2.this));
Log.i("mhsnnn", Preferences.getTempDir(MainActivity2.this));
final int result = Preferences.MENU_ROM_SELECT;
startActivityForResult(myIntent, result);
}
});
dl_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MakeDocCallBack makeDocCallBack = new MakeDocCallBack() {
#Override
public void onResult(ArrayList<String> res) {
if (res.size() > 0) {
try {
jsonObject = new JSONObject(res.get(position));
roms_array.add(jsonObject.getString("downloadlink"));
GetFile fd1 = new GetFile(MainActivity2.this, path_image, getFileName(jsonObject.getString("downloadlink")), jsonObject.getString("downloadlink").toString(),null); //download the bin file
GetFileCallBack roms_callback = new GetFileCallBack() {
#Override
public void onStart() {
}
#Override
public void onProgress(long l, long l1) {
Log.i("nsr", "onProgress");
}
#Override
public void onSuccess() {
Log.i("nsr", "onSuccess");
dl_btn.setVisibility(View.GONE);
run_btn.setVisibility(View.VISIBLE);
}
#Override
public void onFailure() {
Log.i("nsr", "onFailure");
}
};
if (!fd1.DoesFileExist()) {
fd1.Start(roms_callback);
}
} catch (Exception ex) {
}
}
}
};
DocMaker doc = new DocMaker();
doc.set(MainActivity2.this, makeDocCallBack);
}
});
return vi;
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
private boolean verifyExternalStorage() {
// check for sd card first
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// rw access
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// r access
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// no access
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
// if we do not have storage warn user with dialog
if (!mExternalStorageAvailable || !mExternalStorageWriteable) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this)
.setTitle(getString(R.string.app_name) + " Error")
.setMessage("External Storage not mounted, are you in disk mode?")
.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
init();
}
})
.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
dialog.show();
return false;
}
return true;
}
private void init() {
if (verifyExternalStorage() && !_init) {
// always try and make application dirs
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
Log.i("nsrrr1", extStorageDirectory);
// /storage/emulated/0
File myNewFolder = new File(extStorageDirectory + Preferences.DEFAULT_DIR);
Log.i("nsrrr2", extStorageDirectory + Preferences.DEFAULT_DIR);///storage/emulated/0/sega
if (!myNewFolder.exists()) {
myNewFolder.mkdir();
}
myNewFolder = new File(extStorageDirectory + Preferences.DEFAULT_DIR_ROMS);
Log.i("nsrrr3", extStorageDirectory + Preferences.DEFAULT_DIR);///storage/emulated/0/sega
if (!myNewFolder.exists()) {
myNewFolder.mkdir();
}
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list(Preferences.DEFAULT_DIR_GAME);
Log.i("nsrrr3", files + "");
} catch (IOException e) {
Log.e("tag", "Failed to get asset file list.", e);
}
for (String filename : files) {
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open(Preferences.DEFAULT_DIR_GAME + "/" + filename);
File outFile = new File(myNewFolder, filename);
out = new FileOutputStream(outFile);
copyFile(in, out);
} catch (IOException e) {
Log.e("tag", "Failed to copy asset file: " + filename, e);
}
}
// do first run welcome screen
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean firstRun = preferences.getBoolean(Preferences.PREF_FIRST_RUN, true);
if (firstRun) {
// remove first run flag
Editor edit = preferences.edit();
edit.putBoolean(Preferences.PREF_FIRST_RUN, false);
// default input
edit.putBoolean(Preferences.PREF_USE_DEFAULT_INPUT, true);
edit.commit();
}
// generate APK path for the native side
ApplicationInfo appInfo = null;
PackageManager packMgmr = this.getPackageManager();
try {
appInfo = packMgmr.getApplicationInfo(getString(R.string.package_name), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
throw new RuntimeException("Unable to locate assets, aborting...");
}
String _apkPath = appInfo.sourceDir;
// init the emulator
Emulator.init(_apkPath);
Log.i("rrrr", _apkPath);
// set the paths
Emulator.setPaths(extStorageDirectory + Preferences.DEFAULT_DIR,
extStorageDirectory + Preferences.DEFAULT_DIR_ROMS,
"",
"",
"");
// load up prefs now, never again unless they change
//PreferenceFacade.loadPrefs(this, getApplicationContext());
// load gui
// Log.d(LOG_TAG, "Done init()");
setContentView(R.layout.activity_main2);
// set title
super.setTitle(getString(R.string.app_name));
_init = true;
// Log.d(LOG_TAG, "Done onCreate()");
}
}
private void copyFile(InputStream in, OutputStream out) {
byte[] buffer = new byte[1024];
int read;
try {
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
how to make method in my database to do this?
If I understood you properly, you can add a table, user_games for example with User ID, Game ID and Status, then you can update status whenever an action is completed.
For example Status 1 for downloading, status 2 for Downloaded or Finished and you can even add statuses like download failed, to add a re-download button...
you can do something like
public void update_status(UserID,GameID) {
String update = "UPDATE games set status = 1 where id="+Game_ID+" and UserID = " + UserID);
db.rawQuery(update, null);
}

Why List for Recyclerview returning same items in all positions? [duplicate]

This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 5 years ago.
In my android app, I am using recycler view to show items.
(Note: This is not a duplicate question because I tried many answers from stackoverflow but no solution.)
My Problem
The recycler view showing repeated items. A single item is repeating many times even though it occurs only single time in the source DB.
I checked for the reason and note that the List object in Adapter class returning same values in all iterations. But the Fragment that sends List object to adapter class having unique values.
But only the adapter class after receiving the List object contains duplicate items
Solutions I tried
I checked Stackoverflow and added getItemId(int position) and getItemViewType(int position) in adaptor class but no solution
I checked the DB and also List view sending class both dont have duplicate items.
My Code:
InboxHostFragment.java = This class sends List object to adaptor class of recycler view:
public class HostInboxFragment extends Fragment {
View hostinbox;
Toolbar toolbar;
ImageView archive, alert, search;
TextView blank;
Bundle args = new Bundle();
private static final String TAG = "Listinbox_host";
private InboxHostAdapter adapter;
String Liveurl = "";
RelativeLayout layout, host_inbox;
String country_symbol;
String userid;
String login_status, login_status1;
ImageButton back;
String roomid;
RecyclerView listView;
String name = "ramesh";
private int start = 1;
private List < ListFeed > movieList = new ArrayList < > ();
String currency1;
// RecyclerView recyclerView;
public HostInboxFragment() {
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#RequiresApi(api = Build.VERSION_CODES.M)
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
hostinbox = inflater.inflate(R.layout.fragment_host_inbox, container, false);
FontChangeCrawler fontChanger = new FontChangeCrawler(getContext().getAssets(), getString(R.string.app_font));
fontChanger.replaceFonts((ViewGroup) hostinbox);
SharedPreferences prefs = getActivity().getSharedPreferences(Constants.MY_PREFS_NAME, MODE_PRIVATE);
userid = prefs.getString("userid", null);
currency1 = prefs.getString("currenycode", null);
toolbar = (Toolbar) hostinbox.findViewById(R.id.toolbar);
archive = (ImageView) hostinbox.findViewById(R.id.archive);
alert = (ImageView) hostinbox.findViewById(R.id.alert);
search = (ImageView) hostinbox.findViewById(R.id.search);
blank = (TextView) hostinbox.findViewById(R.id.blank);
host_inbox = (RelativeLayout) hostinbox.findViewById(R.id.host_inbox);
layout.setVisibility(View.INVISIBLE);
start = 1;
final String url = Constants.DETAIL_PAGE_URL + "payment/host_reservation_inbox?userto=" + userid + "&start=" + start + "&common_currency=" + currency1;
//*******************************************ListView code start*****************************************************
System.out.println("url in Inbox page===" + url);
movieList.clear();
JsonObjectRequest movieReq = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener < JSONObject > () {
#SuppressWarnings("deprecation")
#Override
public void onResponse(JSONObject response) {
// progressBar.setVisibility(View.GONE);
// Parsing json
// for (int i = 0; i < response.length(); i++) {
try {
JSONArray contact = response.getJSONArray("contact");
obj_contact = contact.optJSONObject(0);
login_status1 = obj_contact.getString("Status");
// progressBar.setVisibility(View.VISIBLE);
layout.setVisibility(View.INVISIBLE);
listView.setVisibility(View.VISIBLE);
host_inbox.setBackgroundColor(Color.parseColor("#FFFFFF"));
ListFeed movie = new ListFeed();
for (int i = 0; i < contact.length(); i++) {
JSONObject obj1 = contact.optJSONObject(i);
movie.getuserby(obj1.getString("userby"));
movie.resid(obj1.getString("reservation_id"));
movie.setresidinbox(obj1.getString("reservation_id"));
System.out.println("reservation iddgdsds" + obj1.getString("reservation_id"));
movie.setuserbys(obj1.getString("userby"));
movie.setuserto(obj1.getString("userto"));
movie.setid(obj1.getString("room_id"));
movie.getid1(obj1.getString("id"));
movie.userto(obj1.getString("userto"));
movie.isread(obj1.getString("isread"));
movie.userbyname(obj1.getString("userbyname"));
country_symbol = obj1.getString("currency_code");
Currency c = Currency.getInstance(country_symbol);
country_symbol = c.getSymbol();
movie.setsymbol(country_symbol);
movie.setTitle(obj1.getString("title"));
movie.setThumbnailUrl(obj1.getString("profile_pic"));
movie.setstatus(obj1.getString("status"));
movie.setcheckin(obj1.getString("checkin"));
movie.setcheckout(obj1.getString("checkout"));
movie.setcreated(obj1.getString("created"));
movie.guest(obj1.getString("guest"));
movie.userbyname(obj1.getString("username"));
movie.getprice(obj1.getString("price"));
String msg = obj1.getString("message");
msg = msg.replaceAll("<b>You have a new contact request from ", "");
msg = msg.replaceAll("</b><br><br", "");
msg = msg.replaceAll("\\w*\\>", "");
movie.message(msg);
movieList.add(movie);
System.out.println(movieList.get(i).message()); // returning unique values
adapter.notifyDataSetChanged();
}
}
} catch (JSONException e) {
e.printStackTrace();
// progressBar.setVisibility(View.GONE);
}
adapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
stopAnim();
//progressBar.setVisibility(View.GONE);
if (error instanceof NoConnectionError) {
Toast.makeText(getActivity(),
"Check your Internet Connection",
Toast.LENGTH_LONG).show();
}
//progressBar.setVisibility(View.GONE);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
movieReq.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
return hostinbox;
}
#Override
public void onStop() {
Log.w(TAG, "App stopped");
super.onStop();
}
#Override
public void onDestroy() {
super.onDestroy();
}
public boolean isOnline(Context c) {
ConnectivityManager cm = (ConnectivityManager) c
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
return ni != null && ni.isConnected();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
In the above code , System.out.println(movieList.get(i).message()); returning unique values without any problem.
Inboxhostadapter.java = This is the adapter for recycleview
public class InboxHostAdapter extends RecyclerView.Adapter < InboxHostAdapter.CustomViewHolder > {
private List < ListFeed > feedItemList;
private ListFeed listFeed = new ListFeed();
String userid = "",
tag,
str_currency;
String reservation_id,
Liveurl,
india2 = "0";
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
String currency1;
String status1;
//private Activity activity;
public Context activity;
public InboxHostAdapter(Context activity, List < ListFeed > feedItemList, String tag) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity);
Liveurl = sharedPreferences.getString("liveurl", null);
userid = sharedPreferences.getString("userid", null);
currency1 = sharedPreferences.getString("currenycode", null);
this.feedItemList = feedItemList; // returning duplicate items
this.activity = activity;
listFeed = new ListFeed();
this.tag = tag;
SharedPreferences prefs1 = activity.getSharedPreferences(Constants.MY_PREFS_LANGUAGE, MODE_PRIVATE);
str_currency = prefs1.getString("currencysymbol", null);
if (str_currency == null) {
str_currency = "$";
}
}
#Override
public InboxHostAdapter.CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.hostinbox, parent, false);
FontChangeCrawler fontChanger = new FontChangeCrawler(activity.getAssets(), activity.getString(R.string.app_font_light));
fontChanger.replaceFonts((ViewGroup) view);
return new CustomViewHolder(view);
}
#Override
public void onBindViewHolder(InboxHostAdapter.CustomViewHolder holder, int position) {
// This block returning duplicate items
listFeed = feedItemList.get(position); // This list feedItemList returning duplicate items
reservation_id = listFeed.getid();
System.out.println("reservation id after getting in inbox adapter" + reservation_id);
System.out.println("check out after getting" + listFeed.getcheckout());
System.out.println("message after getting in inbox adapter" + listFeed.getTitle());
System.out.println("symbol after getting" + listFeed.getsymbol());
System.out.println("username after getting" + listFeed.getaddress());
System.out.println("price after getting" + listFeed.getprice());
System.out.println("status after getting" + listFeed.getstatus());
System.out.println("check in after getting" + listFeed.getcheckin());
System.out.println("check out after getting" + listFeed.getcheckout());
System.out.println("userby after getting====" + listFeed.getuserby());
System.out.println("message after getting====" + listFeed.message());
String msg;
msg = listFeed.message();
holder.name.setText(listFeed.userbyname());
holder.time.setText(listFeed.getcreated());
holder.date1.setText(listFeed.getcheckin());
holder.date2.setText(listFeed.getcheckout());
if (listFeed.guest().equals("1")) {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
} else {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
}
if (tag.equals("Listinbox_service_host")) {
holder.guest.setText("");
holder.ttt.setVisibility(View.INVISIBLE);
} else {
holder.guest.setText(listFeed.guest() + activity.getResources().getString(R.string.guests));
}
// holder.status.setText(listFeed.getstatus());
holder.title.setText(listFeed.getTitle());
status1 = listFeed.getstatus();
if (status1.equals("Accepted")) {
holder.status.setText(activity.getResources().getString(R.string.accepted_details));
}
} else if (status1.equals("Contact Host")) {
holder.status.setText(activity.getResources().getString(R.string.Contact_Host));
holder.guestmsg.setText(listFeed.message());
} else {
holder.status.setText(status1);
}
if (currency1 == null) {
currency1 = "$";
}
if (listFeed.getprice() != null && !listFeed.getprice().equals("null")) {
DecimalFormat money = new DecimalFormat("00.00");
money.setRoundingMode(RoundingMode.UP);
india2 = money.format(new Double(listFeed.getprice()));
holder.currency.setText(listFeed.getsymbol() + " " + india2);
holder.currency.addTextChangedListener(new NumberTextWatcher(holder.currency));
}
//view.imgViewFlag.setImageResource(listFlag.get(position));
System.out.println("listview price" + listFeed.getprice());
System.out.println("listview useds" + listFeed.getresidinbox());
System.out.println("listview dffdd" + listFeed.getuserbys());
System.out.println("listview dfffdgjf" + listFeed.getuserto());
//holder.bucket.setTag(position);
System.out.println("Activity name" + tag);
holder.inbox.setTag(position);
holder.inbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int) v.getTag();
Intent search = new Intent(activity, Inbox_detailshost.class);
search.putExtra("userid", userid);
search.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
activity.startActivity(search);
System.out.println("listview useds" + listFeed.getresidinbox());
System.out.println("listview dffdd" + listFeed.getuserbys());
System.out.println("listview dfffdgjf" + listFeed.getuserto());
}
});
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getItemCount() {
System.out.println("list item size" + feedItemList.size());
return (null != feedItemList ? feedItemList.size() : 0);
}
#Override
public int getItemViewType(int position) {
return position;
}
class CustomViewHolder extends RecyclerView.ViewHolder {
ImageView thumbNail;
TextView name, time, date1, date2, currency, guest, status, title, ttt, guestmsg;
RelativeLayout inbox;
CustomViewHolder(View view) {
super(view);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
this.thumbNail = (ImageView) view.findViewById(R.id.list_image);
this.name = (TextView) view.findViewById(R.id.title2);
this.time = (TextView) view.findViewById(R.id.TextView4);
this.date1 = (TextView) view.findViewById(R.id.TextView2);
this.date2 = (TextView) view.findViewById(R.id.TextView22);
this.currency = (TextView) view.findViewById(R.id.TextView23);
this.guest = (TextView) view.findViewById(R.id.TextView25);
this.ttt = (TextView) view.findViewById(R.id.TextView24);
this.status = (TextView) view.findViewById(R.id.TextView26);
this.title = (TextView) view.findViewById(R.id.TextView28);
this.inbox = (RelativeLayout) view.findViewById(R.id.inbox);
this.guestmsg = (TextView) view.findViewById(R.id.guestmessage);
}
}
public class NumberTextWatcher implements TextWatcher {
private DecimalFormat df;
private DecimalFormat dfnd;
private boolean hasFractionalPart;
private TextView et;
public NumberTextWatcher(TextView et) {
df = new DecimalFormat("#,###");
df.setDecimalSeparatorAlwaysShown(true);
dfnd = new DecimalFormat("#,###.##");
this.et = et;
hasFractionalPart = false;
}
#SuppressWarnings("unused")
private static final String TAG = "NumberTextWatcher";
#Override
public void afterTextChanged(Editable s) {
et.removeTextChangedListener(this);
try {
int inilen, endlen;
inilen = et.getText().length();
String v = s.toString().replace(String.valueOf(df.getDecimalFormatSymbols().getGroupingSeparator()), "");
Number n = df.parse(v);
int cp = et.getSelectionStart();
if (hasFractionalPart) {
et.setText(df.format(n));
} else {
et.setText(dfnd.format(n));
}
endlen = et.getText().length();
int sel = (cp + (endlen - inilen));
if (sel > 0 && sel <= et.getText().length()) {
et.setSelected(true);
}
} catch (NumberFormatException nfe) {
// do nothing?
} catch (ParseException e) {
// do nothing?
}
et.addTextChangedListener(this);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().contains(String.valueOf(df.getDecimalFormatSymbols().getDecimalSeparator()))) {
hasFractionalPart = true;
} else {
hasFractionalPart = false;
}
}
}
}
In the above code , feedItemList returning duplicate values eventhogh the movieList list from source clas Inboxfragment.java contains unique values.
Kindly please help me with this issue. I tried many answers in Stackoverflow but I can't get solutions. I can't figure out the problem.
Use this code
for (int i = 0; i < contact.length(); i++) {
JSONObject obj1 = contact.optJSONObject(i);
ListFeed movie = new ListFeed();
movie.getuserby(obj1.getString("userby"));
movie.resid(obj1.getString("reservation_id"));
movie.setresidinbox(obj1.getString("reservation_id"));
System.out.println("reservation iddgdsds" + obj1.getString("reservation_id"));
movie.setuserbys(obj1.getString("userby"));
movie.setuserto(obj1.getString("userto"));
movie.setid(obj1.getString("room_id"));
movie.getid1(obj1.getString("id"));
movie.userto(obj1.getString("userto"));
movie.isread(obj1.getString("isread"));
movie.userbyname(obj1.getString("userbyname"));
country_symbol = obj1.getString("currency_code");
Currency c = Currency.getInstance(country_symbol);
country_symbol = c.getSymbol();
movie.setsymbol(country_symbol);
movie.setTitle(obj1.getString("title"));
movie.setThumbnailUrl(obj1.getString("profile_pic"));
movie.setstatus(obj1.getString("status"));
movie.setcheckin(obj1.getString("checkin"));
movie.setcheckout(obj1.getString("checkout"));
movie.setcreated(obj1.getString("created"));
movie.guest(obj1.getString("guest"));
movie.userbyname(obj1.getString("username"));
movie.getprice(obj1.getString("price"));
String msg = obj1.getString("message");
msg = msg.replaceAll("<b>You have a new contact request from ", "");
msg = msg.replaceAll("</b><br><br", "");
msg = msg.replaceAll("\\w*\\>", "");
movie.message(msg);
movieList.add(movie);
System.out.println(movieList.get(i).message()); // returning unique value
}
Declare ListFeed movie = new ListFeed(); into the for Loop
And remove the adapter.notifyDataSetChanged(); from for Loop.
I think this help you.

Android Studio music player list view playlist

I do apologize for the noobish question, but I am building a music player in android studio and I am having problems with the songs playing one after the other like a playlist. The songs can only be picked by hand and after the song finishes it just stops until the user clicks another song. I've written two pieces of code that I suspect will solve this issue but I'm not really sure how to implement them or if they eventually will be of any use at all. I would really appreciate some help with this, could really really use it. Any advice or constructive criticism is always welcome, thanks in advance. here are the snippets:
//------------> to get the next song <---------------
int itemsInList=list.getAdapter().getCount();
for(int i=1;i<itemsInList;i++){
list.setSelection(i);
}
//--------------> to play the song on list item click <-------------------
#Override
protected void onListItemClick(ListView list, View view, int position,
long id) {
super.onListItemClick(list, view, position, id);
currentFile = (String) view.getTag();
startPlay(currentFile);
}
And just for reference here is my main java file:
public class MainActivity extends ListActivity {
private static final int UPDATE_FREQUENCY = 500;
private static final int STEP_VALUE = 4000;
private MediaCursorAdapter mediaAdapter = null;
private TextView selectedFile = null;
private SeekBar seekbar = null;
private MediaPlayer player = null;
private ListView list = null;
private ImageButton playButton = null;
private ImageButton prevButton = null;
private ImageButton nextButton = null;
private ImageButton btNext = null;
private ImageButton btPrev = null;
private boolean isStarted = true;
private String currentFile = "";
private boolean isMovingSeekBar = false;
private final Handler handler = new Handler();
private final Runnable updatePositionRunnable = new Runnable() {
public void run() {
updatePosition();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectedFile = (TextView) findViewById(R.id.selectedfile);
seekbar = (SeekBar) findViewById(R.id.seekbar);
playButton = (ImageButton) findViewById(R.id.play);
prevButton = (ImageButton) findViewById(R.id.prev);
nextButton = (ImageButton) findViewById(R.id.next);
btNext = (ImageButton) findViewById(R.id.btNxt);
btPrev = (ImageButton) findViewById(R.id.btPrev);
player = new MediaPlayer();
player.setOnCompletionListener(onCompletion);
player.setOnErrorListener(onError);
seekbar.setOnSeekBarChangeListener(seekBarChanged);
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null, null);
if (null != cursor) {
cursor.moveToFirst();
mediaAdapter = new MediaCursorAdapter(this, R.layout.list_item, cursor);
setListAdapter(mediaAdapter);
playButton.setOnClickListener(onButtonClick);
nextButton.setOnClickListener(onButtonClick);
prevButton.setOnClickListener(onButtonClick);
btNext.setOnClickListener(onButtonClick);
btPrev.setOnClickListener(onButtonClick);
}
}
//----------- ??? ----------------------------------------------------------------
int itemsInList=list.getAdapter().getCount();
for(int i=1;i<itemsInList;i++){
list.setSelection(i);
}
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
currentFile = (String) view.getTag();
startPlay(currentFile);
}
// --------------------------------------------------------------------------------
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(updatePositionRunnable);
player.stop();
player.reset();
player.release();
player = null;
}
private void startPlay(String file) {
Log.i("Selected: ", file);
selectedFile.setText(file);
seekbar.setProgress(0);
player.stop();
player.reset();
try {
player.setDataSource(file);
player.prepare();
player.start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
seekbar.setMax(player.getDuration());
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
isStarted = true;
}
private void stopPlay() {
player.stop();
player.reset();
playButton.setImageResource(android.R.drawable.ic_media_play);
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(0);
isStarted = false;
}
private void updatePosition() {
handler.removeCallbacks(updatePositionRunnable);
seekbar.setProgress(player.getCurrentPosition());
handler.postDelayed(updatePositionRunnable, UPDATE_FREQUENCY);
}
private class MediaCursorAdapter extends SimpleCursorAdapter {
public MediaCursorAdapter(Context context, int layout, Cursor c) {
super(context, layout, c,
new String[]{MediaStore.MediaColumns.DISPLAY_NAME, MediaStore.MediaColumns.TITLE, MediaStore.Audio.AudioColumns.DURATION},
new int[]{R.id.displayname, R.id.title, R.id.duration});
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView title = (TextView) view.findViewById(R.id.title);
TextView name = (TextView) view.findViewById(R.id.displayname);
TextView duration = (TextView) view.findViewById(R.id.duration);
name.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)));
title.setText(cursor.getString(
cursor.getColumnIndex(MediaStore.MediaColumns.TITLE)));
long durationInMs = Long.parseLong(cursor.getString(
cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION)));
double durationInMin = ((double) durationInMs / 1000.0) / 60.0;
durationInMin = new BigDecimal(Double.toString(durationInMin)).setScale(2, BigDecimal.ROUND_UP).doubleValue();
duration.setText("" + durationInMin);
view.setTag(cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA)));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.list_item, parent, false);
bindView(v, context, cursor);
return v;
}
}
private View.OnClickListener onButtonClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play: {
if (player.isPlaying()) {
handler.removeCallbacks(updatePositionRunnable);
player.pause();
playButton.setImageResource(android.R.drawable.ic_media_play);
} else {
if (isStarted) {
player.start();
playButton.setImageResource(android.R.drawable.ic_media_pause);
updatePosition();
} else {
startPlay(currentFile);
}
}
break;
}
case R.id.next: {
int seekto = player.getCurrentPosition() + STEP_VALUE;
if (seekto > player.getDuration())
seekto = player.getDuration();
player.pause();
player.seekTo(seekto);
player.start();
break;
}
case R.id.prev: {
int seekto = player.getCurrentPosition() - STEP_VALUE;
if (seekto < 0)
seekto = 0;
player.pause();
player.seekTo(seekto);
player.start();
break;
}
case R.id.btNxt: {
//TO DO
}
case R.id.btPrev: {
//TO DO
}
}
}
};
private MediaPlayer.OnCompletionListener onCompletion = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlay();
}
};
private MediaPlayer.OnErrorListener onError = new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
return false;
}
};
private SeekBar.OnSeekBarChangeListener seekBarChanged = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
isMovingSeekBar = false;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
isMovingSeekBar = true;
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (isMovingSeekBar) {
player.seekTo(progress);
Log.i("OnSeekBarChangeListener", "onProgressChanged");
}
}
};
}
You can look at my methods below to play the next song. Hope it helps.
public static void nextSong() {
int numOfSong = songList.size();
if (!isShuffle) { // Shuffle mode is off
if (currentPosition < numOfSong - 1) {
currentPosition++;
currentSong = songList.get(currentPosition);
Log.d("my_log", "position = "+currentPosition);
playBackMusic();
} else {
currentPosition = 0;
currentSong = songList.get(currentPosition);
Log.d("my_log", "position = "+currentPosition);
playBackMusic();
}
} else { // Shuffle mode is on
Random rand = new Random();
currentPosition = rand.nextInt(numOfSong);
currentSong = songList.get(currentPosition);
Log.d("my_log", "position = "+currentPosition);
playBackMusic();
}
}
And this is playBackMusic() method to play the song:
public static void playBackMusic() {
try {
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(currentSong.getPath());
mediaPlayer.prepare();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
endOfTheSong();
}
});
isPlaying = true;
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
Method endOfTheSong() to handle what to do after playing current song.
public static void endOfTheSong() {
if (isRepeat == 1) { // currently repeat one song
mediaPlayer.seekTo(0);
mediaPlayer.start();
} else if (isRepeat == 2) { // currently repeat all songs
nextSong();
} else { // currently no repeat
if (currentPosition != songList.size() - 1) nextSong();
}
}

ListView not reflecting the change for notifyDataSetChanged()

What I am doing::
I have three buttons
When I click any one of the button, it must clear adapter & Assign
the newvalues.
The newvalues must reflect in the listview
Problem::
My listview is not reflecting the changes onclick of Button
No log Errors
DisplayBuffet_NotifyDataSetChanged_Fragment.java
public class DisplayBuffet_NotifyDataSetChanged_Fragment extends Fragment implements View.OnClickListener{
// Declaration
static ListView xmlFragmentListView;
static View layout;
static DisplayBuffetAsyncTask downloadTask=null;
Button btnRating,btnPrice,btnDistance;
private FileCache fileCache=null;
private MemoryCache memoryCache=null;
DisplayBuffetAdapter listViewAdapter;
static Bundle bundle=null;
DisplayBuffet_Json_Fragment fragment=null;
ArrayList<HashMap<String, String>> arrayListBuffet=null;
FindMyBuffetDatabaseHelper mHelper=null;;
SQLiteDatabase database=null;
public static DisplayBuffet_NotifyDataSetChanged_Fragment newInstance(FileCache _fileCache,MemoryCache _memoryCache) {
DisplayBuffet_NotifyDataSetChanged_Fragment fragment = new DisplayBuffet_NotifyDataSetChanged_Fragment();
bundle = new Bundle();
bundle.putSerializable(FindMyBuffetConstants.BUFFET_FILECACHE_KEY, _fileCache);
bundle.putSerializable(FindMyBuffetConstants.BUFFET_MEMORYCACHE_KEY, _memoryCache);
fragment.setArguments(bundle);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retain this fragment across configuration changes.
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
layout = inflater.inflate(R.layout.display_buffets_fragment,container, false);
return layout;
}
private void initViews() {
fileCache = (FileCache) getArguments().getSerializable(FindMyBuffetConstants.BUFFET_FILECACHE_KEY);
memoryCache = (MemoryCache) getArguments().getSerializable(FindMyBuffetConstants.BUFFET_MEMORYCACHE_KEY);
xmlFragmentListView = ((ListView) layout.findViewById(R.id.sortrestaurantlistview));
btnRating=(Button) getActivity().findViewById(R.id.btnRating);
btnPrice=(Button) getActivity().findViewById(R.id.btnPrice);
btnDistance=(Button) getActivity().findViewById(R.id.btnDistance);
}
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
arrayListBuffet = new ArrayList<HashMap<String, String>>();
mHelper = new FindMyBuffetDatabaseHelper(FindMyBuffetApplication.currentActivityContext);
database = mHelper.getWritableDatabase();
initViews();
btnRating.setOnClickListener(this);
btnPrice.setOnClickListener(this);
btnDistance.setOnClickListener(this);
setListViewAdapter();
}
#Override
public void onClick(View v) {
String strOrder="asc";
if (FindMyBuffetApplication.isRatingOrderByDesc == false && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_RATING)){
btnRating.setBackgroundResource(R.drawable.tab_button_foucs_asc);
btnPrice.setBackgroundResource(R.drawable.tab_button_default);
btnDistance.setBackgroundResource(R.drawable.tab_button_default);
}
else if (FindMyBuffetApplication.isPriceOrderByDesc == false && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_PRICE)){
btnPrice.setBackgroundResource(R.drawable.tab_button_foucs_asc);
btnRating.setBackgroundResource(R.drawable.tab_button_default);
btnDistance.setBackgroundResource(R.drawable.tab_button_default);
}
else if (FindMyBuffetApplication.isDistanceOrderByDesc == false && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_DISTANCE)){
btnDistance.setBackgroundResource(R.drawable.tab_button_foucs_asc);
btnRating.setBackgroundResource(R.drawable.tab_button_default);
btnPrice.setBackgroundResource(R.drawable.tab_button_default);
}
else if (FindMyBuffetApplication.isRatingOrderByDesc == true && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_RATING)){
btnRating.setBackgroundResource(R.drawable.tab_button_foucs_dec);
btnDistance.setBackgroundResource(R.drawable.tab_button_default);
btnPrice.setBackgroundResource(R.drawable.tab_button_default);
}
else if (FindMyBuffetApplication.isPriceOrderByDesc == true && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_PRICE)){
btnPrice.setBackgroundResource(R.drawable.tab_button_foucs_dec);
btnDistance.setBackgroundResource(R.drawable.tab_button_default);
btnRating.setBackgroundResource(R.drawable.tab_button_default);
}
else if (FindMyBuffetApplication.isDistanceOrderByDesc == true && FindMyBuffetApplication.sortBy.equalsIgnoreCase(FindMyBuffetConstants.TAB_NAME_DISTANCE)){
btnDistance.setBackgroundResource(R.drawable.tab_button_foucs_dec);
btnPrice.setBackgroundResource(R.drawable.tab_button_default);
btnRating.setBackgroundResource(R.drawable.tab_button_default);
}
switch(v.getId()) {
case R.id.btnRating:
FindMyBuffetApplication.sortBy = FindMyBuffetConstants.TAB_NAME_RATING;
if (FindMyBuffetApplication.isRatingOrderByDesc == false)
FindMyBuffetApplication.isRatingOrderByDesc = true;
else
FindMyBuffetApplication.isRatingOrderByDesc = false;
//displayView();
if(FindMyBuffetApplication.isRatingOrderByDesc==true)strOrder="desc";
sortListView(FindMyBuffetConstants.SORT_BY_RATING_1,strOrder);
break;
case R.id.btnPrice:
FindMyBuffetApplication.sortBy = FindMyBuffetConstants.TAB_NAME_PRICE;
if (FindMyBuffetApplication.isPriceOrderByDesc == false)
FindMyBuffetApplication.isPriceOrderByDesc = true;
else
FindMyBuffetApplication.isPriceOrderByDesc = false;
//displayView();
if(FindMyBuffetApplication.isPriceOrderByDesc==true)strOrder="desc";
sortListView(FindMyBuffetConstants.SORT_BY_PRICE_1,strOrder);
break;
case R.id.btnDistance:
FindMyBuffetApplication.sortBy = FindMyBuffetConstants.TAB_NAME_DISTANCE;
if (FindMyBuffetApplication.isDistanceOrderByDesc == false)
FindMyBuffetApplication.isDistanceOrderByDesc = true;
else
FindMyBuffetApplication.isDistanceOrderByDesc = false;
//displayView();
if(FindMyBuffetApplication.isPriceOrderByDesc==true)strOrder="desc";
sortListView(FindMyBuffetConstants.SORT_BY_DISTANCE_1,strOrder);
break;
}
}
private void setListViewAdapter(){
downloadTask = new DisplayBuffetAsyncTask();
if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_RATING){
if (FindMyBuffetApplication.isDownloading) {
downloadTask.initilizeAsyncTask(
getFragmentManager(), xmlFragmentListView,downloadTask,
fileCache,memoryCache);
downloadTask.execute();
}
}
else if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_PRICE){
if (FindMyBuffetApplication.isDownloading) {
downloadTask.initilizeAsyncTask(
getFragmentManager(), xmlFragmentListView,
downloadTask,
fileCache,memoryCache);
downloadTask.execute();
}
}
else if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_DISTANCE){
if (FindMyBuffetApplication.isDownloading) {
downloadTask.initilizeAsyncTask(
getFragmentManager(), xmlFragmentListView,
downloadTask,
fileCache,memoryCache);
downloadTask.execute();
}
}
listViewAdapter = new DisplayBuffetAdapter(arrayListBuffet, fileCache,memoryCache);
xmlFragmentListView.setAdapter(listViewAdapter);
}
private void sortListView(String strSortBy,String strOrder) {
arrayListBuffet.clear();
if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_RATING) {
SortBuffets(FindMyBuffetConstants.SORT_BY_RATING_1, strOrder);
} else if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_PRICE) {
SortBuffets(FindMyBuffetConstants.SORT_BY_PRICE_1, strOrder);
} else if (FindMyBuffetApplication.sortBy == FindMyBuffetConstants.TAB_NAME_DISTANCE) {
SortBuffets(FindMyBuffetConstants.SORT_BY_DISTANCE_1, strOrder);
}
listViewAdapter.notifyDataSetChanged();
}
/*#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
}*/
private void displayView() {
Fragment objFragment = getFragmentManager().findFragmentById(getId());
if (objFragment != null) {
getFragmentManager().beginTransaction().remove(objFragment).commit();
//objFragment = new SortBuffetRating();
objFragment = DisplayBuffet_Json_Fragment.newInstance(fileCache,memoryCache);
getFragmentManager().beginTransaction().add(R.id.frame_container, objFragment).commit();
} else {
//objFragment = new SortBuffetRating();
objFragment = DisplayBuffet_Json_Fragment.newInstance(fileCache,memoryCache);
getFragmentManager().beginTransaction().add(R.id.frame_container, objFragment).commit();
}
}
/*
* Displays data from SQLite
*/
private void SortBuffets(String strSortBy,String strOrder){
Cursor mCursor = database.rawQuery("select * from " + BuffetTable.TABLE_NAME_BUFFET + " order by " + strSortBy +" "+strOrder, null);
try {
// looping through all rows and adding to list
if (mCursor.moveToFirst()) {
do {
HashMap<String, String> map=new HashMap<String, String>();
map.put(BuffetTable.COLUMN_ID,mCursor.getString(0));
map.put(BuffetTable.COLUMN_BUF_OFF_ID,mCursor.getString(1));
map.put(BuffetTable.COLUMN_FROM_TIME,mCursor.getString(2));
map.put(BuffetTable.COLUMN_TO_TIME,mCursor.getString(3));
map.put(BuffetTable.COLUMN_ONLINE_PRICE,mCursor.getString(4));
map.put(BuffetTable.COLUMN_RESERVED_PRICE,mCursor.getString(5));
map.put(BuffetTable.COLUMN_BUF_IMAGE_FILE_NAME,mCursor.getString(6));
map.put(BuffetTable.COLUMN_RES_NAME,mCursor.getString(7));
map.put(BuffetTable.COLUMN_RATING,mCursor.getString(8));
map.put(BuffetTable.COLUMN_LATITUDE,mCursor.getString(9));
map.put(BuffetTable.COLUMN_LONGITUDE,mCursor.getString(10));
map.put(BuffetTable.COLUMN_BUF_TYPE_NAME,mCursor.getString(11));
arrayListBuffet.add(map);
} while (mCursor.moveToNext());
}
}catch (SQLiteException e){
Log.i(FindMyBuffetApplication.applicationName+"."+FindMyBuffetConstants.PACKAGE_NAME+"."+FindMyBuffetConstants.PACKAGE_NAME,"Error Druing Sorting Buffets "+ e.getMessage());
e.printStackTrace();
Toast.makeText(FindMyBuffetApplication.currentActivityContext, "Error Druing Sorting The Buffets By" +strSortBy,Toast.LENGTH_LONG).show();
}catch (Exception e) {
Log.i(FindMyBuffetApplication.applicationName+"."+FindMyBuffetConstants.PACKAGE_NAME+"."+FindMyBuffetConstants.PACKAGE_NAME,"Error Druing Sorting Buffets "+ e.getMessage());
e.printStackTrace();
Toast.makeText(FindMyBuffetApplication.currentActivityContext, "Error Druing Sorting The Buffets By" +strSortBy,Toast.LENGTH_LONG).show();
}finally {
// Release the memory
mCursor.close();
}
}
#Override
public void onDestroy() {
super.onDestroy();
database.close();
//layout = null; // now cleaning up!
//bundle = null;
/*fragment = null;
if (downloadTask != null && downloadTask.getStatus() != AsyncTask.Status.FINISHED)
downloadTask=null;*/
}
}
DisplayBuffetAdapter.java
public class DisplayBuffetAdapter extends BaseAdapter {
// Declare Variables
ImageLoader imageLoader;
ArrayList<HashMap<String, String>> arrayListBuffet;
LayoutInflater inflater;
FileCache fileCache=null;
MemoryCache memoryCache=null;
int tmpLoopCnt=0;
public DisplayBuffetAdapter(ArrayList<HashMap<String, String>> _arraylist,FileCache _fileCache,MemoryCache _memoryCache) {
this.arrayListBuffet = _arraylist;
this.fileCache=_fileCache;
this.memoryCache=_memoryCache;
this.imageLoader=new ImageLoader(FindMyBuffetApplication.currentActivityContext,fileCache,memoryCache);
tmpLoopCnt=0;
}
public int getCount() {
return arrayListBuffet.size();
}
public Object getItem(int position) {
return arrayListBuffet.get(position);
}
public long getItemId(int position) {
return position;
}
private class ViewHolder {
// Declare Variables
ImageView imgRestBuffLogo;
TextView txtResName;
TextView txtRestBufType;
TextView txtRestTime;
TextView txtRestDistance;
TextView txtReservePrice;
TextView txtOnlinePrice;
RatingBar restRatingBar;
Button btnOnlinePrice;
Button btnReservedPrice;
}
public View getView(int position, View convertView, ViewGroup parent) {
tmpLoopCnt = tmpLoopCnt + 1;
Log.i("LIST VIEW ADAPATER COUNT", ""+tmpLoopCnt);
ViewHolder holder;
LayoutInflater inflater;
if (convertView == null) {
inflater = (LayoutInflater) FindMyBuffetApplication.currentActivityContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.display_buffet_listview, null);
holder = new ViewHolder();
Typeface txtResnameFontFace=Typeface.createFromAsset(FindMyBuffetApplication.currentActivityContext.getAssets(), "Roboto-Bold.ttf");
Typeface txtRestBufTypeFontFace=Typeface.createFromAsset(FindMyBuffetApplication.currentActivityContext.getAssets(), "Roboto-Medium.ttf");
Typeface txtRestTimeFontFace=Typeface.createFromAsset(FindMyBuffetApplication.currentActivityContext.getAssets(), "Roboto-Bold.ttf");
//Typeface txtReservePrice=Typeface.createFromAsset(FindMyBuffetApplicationCls.currentActivityContext.getAssets(),"Roboto-Bold.ttf");
//Typeface txtOnlinePrice=Typeface.createFromAsset(FindMyBuffetApplicationCls.currentActivityContext.getAssets(),"Roboto-Bold.ttf");
Typeface btnPrice=Typeface.createFromAsset(FindMyBuffetApplication.currentActivityContext.getAssets(), "Roboto-Bold.ttf");
Typeface txtRestDistanceFontFace=Typeface.createFromAsset(FindMyBuffetApplication.currentActivityContext.getAssets(),"Roboto-Light.ttf");
// Locate the TextViews in listview_item.xml
holder.txtResName = (TextView) convertView.findViewById(R.id.txtRestName);
holder.txtResName.setTypeface(txtResnameFontFace);
holder.txtRestBufType = (TextView) convertView.findViewById(R.id.txtRestBufType);
holder.txtRestBufType.setTypeface(txtRestBufTypeFontFace);
holder.txtRestTime = (TextView) convertView.findViewById(R.id.txtRestTime);
holder.txtRestTime.setTypeface(txtRestTimeFontFace);
holder.txtRestDistance = (TextView) convertView.findViewById(R.id.txtRestDistance);
holder.txtRestDistance.setTypeface(txtRestDistanceFontFace);
holder.restRatingBar=(RatingBar) convertView.findViewById(R.id.restRatingBar);
//holder.txtReservePrice = (TextView) convertView.findViewById(R.id.txtReservePrice);
//holder.txtReservePrice.setTypeface(txtReservePrice);
//holder.txtOnlinePrice = (TextView) convertView.findViewById(R.id.txtOnlinePrice);
//holder.txtOnlinePrice.setTypeface(txtOnlinePrice);
holder.btnOnlinePrice=(Button) convertView.findViewById(R.id.btnOnlinePrice);
holder.btnOnlinePrice.setTypeface(btnPrice);
holder.btnReservedPrice=(Button) convertView.findViewById(R.id.btnReservedPrice);
holder.btnOnlinePrice.setTypeface(btnPrice);
// Locate the ImageView in listview_item.xml
holder.imgRestBuffLogo = (ImageView) convertView.findViewById(R.id.imgRestBuffetLogo);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
HashMap<String, String> objMap= arrayListBuffet.get(position);
holder.txtResName.setText(objMap.get(BuffetTable.COLUMN_RES_NAME));
holder.txtRestBufType.setText(objMap.get(BuffetTable.COLUMN_BUF_TYPE_NAME));
holder.restRatingBar.setRating(Float.valueOf(objMap.get(BuffetTable.COLUMN_RATING)));
holder.txtRestTime.setText(formatTime(objMap.get(BuffetTable.COLUMN_FROM_TIME))+" to "+formatTime(objMap.get(BuffetTable.COLUMN_TO_TIME)));
//txtOnlinePrice.setText(objMap.get("Online_Price"));
//txtReservePrice.setText(objMap.get("Reserved_Price"));
holder.btnOnlinePrice.setText(" Buy Now\n "+"Rs."+objMap.get(BuffetTable.COLUMN_ONLINE_PRICE)+" ");
holder.btnReservedPrice.setText(" Reserve\n "+"Rs."+objMap.get(BuffetTable.COLUMN_RESERVED_PRICE)+" ");
//double dist=objMap.get("Latitude")-objMap.get("Longitude");
//txtRestDistance.setText(String.valueOf(dist));
holder.txtRestDistance.setText(""+10+position+" Km");
String strUrl=FindMyBuffetApplication.URL+FindMyBuffetConstants.WEB_SERVER_PATH_BUF_IMAGE+objMap.get(BuffetTable.COLUMN_BUF_IMAGE_FILE_NAME);
imageLoader.DisplayImage(strUrl,holder.imgRestBuffLogo);
return convertView;
}
private String formatTime(String strTime){
//example For hour,minutes and seconds
// String strTime = "15:30:18 pm";
//SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss a");
strTime=strTime.substring(0,5)+" am";
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
Date date = null;
try {
date = sdf.parse(strTime);
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sdf.format(date);
}
}
in private void sortListView(
before calling notifyDataSetChanged, you should submit the new dataset to your adapter. Otherwise you are only chaining the data inside the fragment. You could this both creating a new Adapter and calling setListAdapter again, or creating a method inside the Adapter to update the dataset. For instance:
public void updateData(ArrayList<HashMap<String, String>> _arraylist) {
this.arrayListBuffet = _arraylist;
}
and call it before
listViewAdapter.notifyDataSetChanged();
When you sort you are in fact adding to arrayListBuffet but that may not be your only problem. What you're doing is sorting an array that's not inside the adapter, you need to pass the newly sorted data, in your case arrayListBuffet back to the adapter before calling notifyDataSetChanged
Why? Because if you don't, the data that the adapter is using is still the one from when you initialised it, and therefore you'll see no changes. In other words, you didn't really change the dataset it's using.
How? You can create a method in your adapter and pass the newly sorted data source as a parameter, replacing the original content, you can actually call the notifyDataSetChanged from within that same method.
Code
In your adapter:
public void updateDataSource(ArrayList<HashMap<String, String>> sortedArrayListBuffet) {
this.arrayListBuffet = sortedArrayListBuffet;
this.notifyDataSetChanged();
}

Categories