ContactsContract.Contacts issue, duplicates - cursor

I've been doing research on this but I can't figure it out. My contacts in my phone in a sample app I downloaded are often duplicated, like so:
I'm quite sure it has something to do with ContactsContract.Contacts. I've read up on it but don't know how to implement it in my code. Could someone help (or indeed if there's another way of doing it). I just want each contact be listed once, not multiple time.
According to http://developer.android.com/reference/android/provider/ContactsContract.Contacts.html :
ContactsContract.Contacts
Constants for the contacts table, which contains a record per aggregate of raw contacts representing the same person.
I have 3 java files in my project, MainActivity, SelectUser and SelectUserAdapter, but I believe MainActivity is the one pertaining to this problem. Probably specifically this line :
phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
If you need more code just let me know.
Here's my MainActivity.java :
package com.example.chris.contactlistcustomlistview;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
// ArrayList
ArrayList<SelectUser> selectUsers;
List<SelectUser> temp;
// Contact List
ListView listView;
// Cursor to load contacts list
Cursor phones, email;
// Pop up
ContentResolver resolver;
SearchView search;
SelectUserAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
selectUsers = new ArrayList<SelectUser>();
resolver = this.getContentResolver();
listView = (ListView) findViewById(R.id.contacts_list);
phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
// retrieves contact information
LoadContact loadContact = new LoadContact();
loadContact.execute();
// let's set up our search box,
search = (SearchView) findViewById(R.id.searchView);
//*** setOnQueryTextListener ***
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
// when the text in searchView changes, call the filter function
adapter.filter(newText);
return false;
}
});
}
// Load data on background
class LoadContact extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
// Get Contact list from Phone
if (phones != null) {
Log.e("count", "" + phones.getCount());
if (phones.getCount() == 0) {
Toast.makeText(MainActivity.this, "No contacts in your contact list.", Toast.LENGTH_LONG).show();
}
while (phones.moveToNext()) {
Bitmap bit_thumb = null;
String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
String EmailAddr = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA2));
String image_thumb = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI));
try {
if (image_thumb != null) {
bit_thumb = MediaStore.Images.Media.getBitmap(resolver, Uri.parse(image_thumb));
} else {
Log.e("No Image Thumb", "--------------");
}
} catch (IOException e) {
e.printStackTrace();
}
//what's happening here? For every user in the phonebook, show an image, the name, number, an id and maybe a checkbox?
SelectUser selectUser = new SelectUser();
selectUser.setThumb(bit_thumb);
selectUser.setName(name);
selectUser.setPhone(phoneNumber);
selectUser.setEmail(id);
selectUser.setCheckedBox(false);
selectUsers.add(selectUser);
}
} else {
Log.e("Cursor close 1", "----------------");
}
//phones.close();
return null;
}
#Override
// when DoInBackground is finished, when we have our phone number, name etc... display the results in our listview.
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter = new SelectUserAdapter(selectUsers, MainActivity.this);
listView.setAdapter(adapter);
// Select item on listclick
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.e("search", "here---------------- listener");
SelectUser data = selectUsers.get(i);
}
});
listView.setFastScrollEnabled(true);
}
}
#Override
protected void onStop() {
super.onStop();
phones.close();
}
}

public class MainActivity extends Activity {
Cursor cursor;
ListView mainListView;
ArrayList hashMapsArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (cursor != null) {
cursor.moveToFirst();}
try {
cursor = getApplicationContext().getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
int Idx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID);
int nameIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int phoneNumberIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int photoIdIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI);
cursor.moveToFirst();
Set<String> ids = new HashSet<>();
do {
System.out.println("=====>in while");
String contactid=cursor.getString(Idx);
if (!ids.contains(contactid)) {
ids.add(contactid);
HashMap<String, String> hashMap = new HashMap<String, String>();
String name = cursor.getString(nameIdx);
String phoneNumber = cursor.getString(phoneNumberIdx);
String image = cursor.getString(photoIdIdx);
System.out.println("Id--->"+contactid+"Name--->"+name);
System.out.println("Id--->"+contactid+"Name--->"+name);
System.out.println("Id--->"+contactid+"Number--->"+phoneNumber);
if (!phoneNumber.contains("*")) {
hashMap.put("contactid", "" + contactid);
hashMap.put("name", "" + name);
hashMap.put("phoneNumber", "" + phoneNumber);
hashMap.put("image", "" + image);
// hashMap.put("email", ""+email);
if (hashMapsArrayList != null) {
hashMapsArrayList.add(hashMap);}
// hashMapsArrayList.add(hashMap);
}
}
} while (cursor.moveToNext());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}

Related

Incompatible types. Found: 'java.util.ArrayList<java.lang.Object>', required: 'java.util.ArrayList<UserLocation>'

So I am creating a route planner app in Android Studio and its giving me the error in the title of this question
Heres my code
import android.Manifest;
import android.app.Fragment;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import com.example.destinationrouteplanner.R;
import com.example.destinationrouteplanner.adapters.UserRecyclerAdapter;
import com.example.destinationrouteplanner.models.MarkerCluster;
import com.example.destinationrouteplanner.models.User;
import com.example.destinationrouteplanner.util.MyClusterManagerRenderer;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLngBounds;
import com.google.maps.android.clustering.ClusterManager;
import java.util.ArrayList;
public class UserListFragment extends Fragment implements OnMapReadyCallback
{
private static final String TAG = "UserListFragment";
private RecyclerView mUserListRecyclerView;
private MapView mMapView;
private ArrayList<User> mUserList = new ArrayList<>();
//private UserRecyclerAdapter mUserRecyclerAdapter;
private ArrayList<UserLocation> mUserLocations = new ArrayList<>();
private UserRecyclerAdapter mUserRecyclerAdapter;
private GoogleMap mGoogleMap;
private LatLngBounds mMapBoundary;
private UserLocation mUserPosition;
private ClusterManager mClusterManager;
private MyClusterManagerRenderer mClusterManagerRenderer;
private ArrayList<MarkerCluster> mClusterMarkers = new ArrayList<>();
public static UserListFragment newInstance() {
return new UserListFragment();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mUserList = getArguments().getParcelableArrayList(getString(R.string.intent_user_list));
}
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_user_list, container, false);
mUserListRecyclerView = view.findViewById(R.id.user_list_recycler_view);
mMapView = view.findViewById(R.id.user_list_map);
initUserListRecyclerView();
initGoogleMap(savedInstanceState);
return view;
}
private void initGoogleMap(Bundle savedInstanceState){
// *** IMPORTANT ***
// MapView requires that the Bundle you pass contain _ONLY_ MapView SDK
// objects or sub-Bundles.
Bundle mapViewBundle = null;
if (savedInstanceState != null) {
mapViewBundle = savedInstanceState.getBundle(MAPVIEW_BUNDLE_KEY);
}
mMapView.onCreate(mapViewBundle);
mMapView.getMapAsync(this);
}
private void initUserListRecyclerView() {
mUserRecyclerAdapter = new UserRecyclerAdapter(mUserList);
mUserListRecyclerView.setAdapter(mUserRecyclerAdapter);
mUserListRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Bundle mapViewBundle = outState.getBundle(MAPVIEW_BUNDLE_KEY);
if (mapViewBundle == null) {
mapViewBundle = new Bundle();
outState.putBundle(MAPVIEW_BUNDLE_KEY, mapViewBundle);
}
mMapView.onSaveInstanceState(mapViewBundle);
}
#Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
#Override
public void onStart() {
super.onStart();
mMapView.onStart();
}
#Override
public void onStop() {
super.onStop();
mMapView.onStop();
}
#Override
public void onMapReady(GoogleMap map) {
if (ActivityCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
map.setMyLocationEnabled(true);
mGoogleMap = map;
addMapMarkers();
}
#Override
public void onPause() {
mMapView.onPause();
super.onPause();
}
#Override
public void onDestroy() {
mMapView.onDestroy();
super.onDestroy();
}
#Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
private void addMapMarkers()
{
if (mGoogleMap !=null)
{
if(mClusterManager == null)
{
mClusterManager = new ClusterManager<MarkerCluster>(getActivity().getApplicationContext(), mGoogleMap);
}
if (mClusterManagerRenderer == null)
{
mClusterManagerRenderer = new MyClusterManagerRenderer(getActivity(), mGoogleMap, mClusterManager);
mClusterManager.setRenderer(mClusterManagerRenderer);
}
for (UserLocation userLocation: mUserLocations)
{
Log.d(TAG, "AddMapMarkers: location: " + userLocation.getGeo_point().toString());
try {
String snippet = "";
if (userLocation.getUser().getUser_id().equals(FirebaseAuth.getInstance().getUid()))
{
snippet = "This is you";
}else {
snippet = "Determine route to " + userLocation.getUser().getUsername() + "?";
}
int avatar = R.drawable.cwm_logo; //Set the default avatar
try {
avatar = Integer.parseInt(userLocation.getUser().getAvatar());
}catch (NumberFormatException e)
{
Log.d(TAG, "addMapMarkers: no avatar for: " + userLocation.getUser().getUsername() + ", setting default");
}
MarkerCluster newMarkerCluster = new MarkerCluster(new LatLng(userLocation.getGeo_point().getLatitude(), userLocation.getGeo_point().getLongitude(), userLocation.getUser().getUsername(), snippet, avatar, userLocation.getUser()));
mClusterManager.addItem(newMarkerCluster);
mClusterMarkers.add(newMarkerCluster);
}catch (NullPointerException e)
{
Log.e(TAG "addMapMarkers: NullPointerException: " + e.getMessage());
}
}
mClusterManager.cluster();
setCameraView();
}
}
private void setCameraView()
{
double bottomBoundary = mUserPosition.getGeo_point().getLatitude() - .1;
double leftBoundary = mUserPosition.getGeo_point().getLongitude() - .1;
double topBoundary = mUserPosition.getGeo_point().getLatitude() - .1;
double rightBoundary = mUserPosition.getGeo_point().getLongitude() - .1;
}
#Override
public void onMapReady(#NonNull GoogleMap googleMap) {
}
}
I tired using the answer to this question but not working
Required type:
ArrayList
Provided:
ArrayList
no instance(s) of type variable(s) exist so that UserLocation conforms to Object

Implemented methods are not working in native interface(android) for Fused location provider

I'm trying to apply FusedLocation provider in cn1 through native interface(android). I've implemented ConnectionCallbacks and OnConnectionFailedListener interfaces. It generates methods like onConnected(), onConnectionSuspended() and onConnectionFailed() in native android, which are not working when app is built in cn1.
Moreover, lifecycle methods like onResume, onDestroy of FusedLocationImpl etc are also not working. In the coming days, I'm planning to create the fused GPS library for general purpose as well.
PS. There are no build errors and got no any other errors when debugged.
FusedLocationImpl.java
import com.codename1.impl.android.AndroidNativeUtil;
import android.os.Bundle;
import android.location.Location;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationAvailability;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationListener;
public class FusedLocationImpl implements GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
private Location mLastLocation;
private LocationRequest mLocationRequest;
public boolean isSupported() {
return true;
}
public void getFusedLocationPermission() {
if (!com.codename1.impl.android.AndroidNativeUtil.checkForPermission(Manifest.permission.ACCESS_FINE_LOCATION, "Please allow location permission")) {
}
}
public void fusedLocation() {
if (checkPlayServices()) {
buildGoogleApiClient();
}
}
public void onConnected(Bundle bundle) { // not working...
Log.i("onConnected", "GoogleApiClient connected!");
createLocationRequest();
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Log.i("onConnected", " Location: " + mLastLocation);
}
protected void createLocationRequest() { // not working...
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, new LocationCallback() {
#Override
public void onLocationResult(final LocationResult locationResult) {
Log.i("onLocationResult",locationResult + "");
}
#Override
public void onLocationAvailability(LocationAvailability locationAvailability) {
Log.i("onLocationAvailability", "onLocationAvailability: isLocationAvailable = " + locationAvailability.isLocationAvailable());
}
}, null);
}
public void onConnectionSuspended(int i) {
mGoogleApiClient.connect();
}
public void onConnectionFailed(ConnectionResult result) {
Log.i("onConnectionFailed", "Connection failed: ConnectionResult.getErrorCode() = "
+ result.getErrorCode());
}
public void onPause() {
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (LocationListener) this);
mGoogleApiClient.disconnect();
}
}
public void onResume() {
checkPlayServices();
}
public void onStart() {
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
Log.i("onStart", "mGoogleApiClient.connect()");
}
}
public void onDestroy() {
Log.i("onDestory", "Service destroyed!");
mGoogleApiClient.disconnect();
}
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(AndroidNativeUtil.getActivity());
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, AndroidNativeUtil.getActivity(),
PLAY_SERVICES_RESOLUTION_REQUEST).show();
} else {
AndroidNativeUtil.getActivity().finish();
}
return false;
}
return true;
}
protected synchronized void buildGoogleApiClient() {
Log.i("buildGoogleApiClient", "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(AndroidNativeUtil.getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
FusedLocation.java
public interface FusedLocation extends NativeInterface{
public void getFusedLocationPermission();
public void fusedLocation();
}
MyApplication.java
public void start() {
if (current != null) {
current.show();
return;
}
Form hi = new Form("Hi World", BoxLayout.y());
hi.show();
Button btn = new Button("ask for permission");
FusedLocation fl = (FusedLocation) NativeLookup.create(FusedLocation.class);
Button btn1 = new Button("fused network");
hi.add(btn1);
btn1.addActionListener(e->{
if (fl != null && fl.isSupported()) {
fl.getFusedLocationPermission();
fl.fusedLocation();
System.out.println("fusedLocation");
}
});
}
PS. permission for location (ACCESS_FINE_LOCATION) succeeds. The main issue I've got is onConnected() and other implemented methods are not called. Thankyou
cn1 Location manager: this is not giving quite a performance as the native fused location provider
public final void checkGPS() {
if (Display.getInstance().getLocationManager().isGPSDetectionSupported()) {
if (Display.getInstance().getLocationManager().isGPSEnabled()) {
InfiniteProgress ip = new InfiniteProgress();
final Dialog ipDlg = ip.showInifiniteBlocking();
//Cancel after 20 seconds
Location loc = LocationManager.getLocationManager().getCurrentLocationSync(20000);
ipDlg.dispose();
if (loc != null) {
lat = loc.getLatitude();
lng = loc.getLongitude();
Dialog.show("location", "lat: " + lat + " lon: " + lng, "ok", null);
} else {
Dialog.show("GPS error", "Your location could not be found, please try going outside for a better GPS signal", "Ok", null);
}
} else {
Dialog.show("GPS disabled", "AppName needs access to GPS. Please enable GPS", "Ok", null);
}
} else {
Dialog.show("Warning", "GPS is not supported in your device", "ok", null);
}
}
I'm not sure why you aren't using the location listener which uses fused location internally when play services is enabled (the default).
You asked for permissions in the XML but didn't use the Android 6+ permissions which need a different syntax. Again, if you just use the location API this is all seamless...

I am unable to get video to play reliably in codenameone

I am at the point of abandoning using codenameone to build an app that allows me to play video from storage or to capture and play. Its either it is playing but no video is showing (most common ) or it plays only once and thats it - the fast forward and rewind buttons not working. I don't know if this is a simulator problem/limitation or whether I just don't know what I am doing.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.ixzdore.ziem.renderer.widgets;
import com.codename1.capture.Capture;
import com.codename1.components.ImageViewer;
import com.codename1.components.MediaPlayer;
import com.codename1.io.FileSystemStorage;
import com.codename1.io.Log;
import static com.codename1.io.Log.e;
import com.codename1.media.Media;
import com.codename1.media.MediaManager;
import com.codename1.ui.Container;
import com.codename1.ui.Display;
import com.codename1.ui.Image;
import com.codename1.ui.Label;
import com.codename1.ui.events.ActionEvent;
import com.codename1.ui.events.ActionListener;
import com.codename1.ui.geom.Dimension;
import com.codename1.ui.layouts.BorderLayout;
import com.ixzdore.ziem.models.DocumentElement;
import com.ixzdore.ziem.models.ReportDocument;
import java.io.IOException;
/**
*
* #author jamesagada
*/
public class NVideo extends Widget {
private final Label _imageLabel = new Label();
private MediaPlayer _mPlayer;
private Container imageVideoContainer;
public NVideo(DocumentElement element, ReportDocument doc, Boolean isEditing) {
super(element, doc, isEditing);
imageVideoContainer = new Container(new BorderLayout(BorderLayout.CENTER_BEHAVIOR_SCALE)) {
protected Dimension calcPreferredSize() {
return new Dimension(Display.getInstance().getDisplayWidth(), Display.getInstance().getDisplayWidth());
}
};
_mPlayer = new MediaPlayer();
setupWidgetFromProperty();
}
#Override
public void renderEdit() {
//super.initLayout();
super.setEnabled(true);
}
public void renderSummary() {
//super.initLayout();
super.setEnabled(false);
getIconContainer().remove();
revalidate();
}
#Override
public void renderView() {
//find the
//super.initLayout();
super.setEnabled(false);
getIconContainer().remove();
revalidate();
}
#Override
public void setupWidgetFromProperty() {
super.setupWidgetFromProperty();
String videoFile = documentElement.getVideoFileFromValue(documentElement.getPropertyValue());
if (videoFile != null) {
try {
Media video = MediaManager.createMedia(videoFile, true);
if (_mPlayer == null) {
_mPlayer = new MediaPlayer();
}
_mPlayer.setDataSource(videoFile);
_mPlayer.setAutoplay(true);
if (imageVideoContainer == null) {
imageVideoContainer = new Container(new BorderLayout(BorderLayout.CENTER_BEHAVIOR_SCALE)) {
protected Dimension calcPreferredSize() {
return new Dimension(Display.getInstance().getDisplayWidth(), Display.getInstance().getDisplayWidth() );
}
};
}
getWidgetContainer().removeAll();
imageVideoContainer.add(BorderLayout.CENTER, _mPlayer);
imageVideoContainer.revalidate();
getWidgetContainer().add(imageVideoContainer);
getWidgetContainer().revalidate();
getWidgetContainer().repaint();
documentElement.setPropertyValue(videoFile);
} catch (Exception err) {
Log.e(err);
}
}
}
#Override
public void setupPropertyButtons() {
super.setupPropertyButtons();
//add a capture button and a browse button for gallery
//save captured picture and put the URL value in the propertyValue
final Widget _this = this;
_captureButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
//open the capture button and take a video
String photoFile = Capture.captureVideo();
if (photoFile != null) {
try {
_mPlayer.setDataSource(photoFile);
_mPlayer.setAutoplay(false);
_mPlayer.revalidate();
_mPlayer.repaint();
imageVideoContainer.revalidate();
_this.revalidate();
documentElement.setPropertyValue(photoFile);
} catch (Exception err) {
Log.e(err);
}
}
}
});
_captureButton.setText("");
getIconContainer().add(_captureButton);
getIconContainer().revalidate();
getIconContainer().repaint();
getLabelContainer().repaint();
_findButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
Display.getInstance().openGallery(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
if (ev != null && ev.getSource() != null) {
String file = (String) ev.getSource();
try {
_mPlayer.setDataSource(file);
_mPlayer.setAutoplay(false);
_mPlayer.revalidate();
_mPlayer.repaint();
imageVideoContainer.revalidate();
imageVideoContainer.repaint();
_this.revalidate();
documentElement.setPropertyValue(file);
} catch (Exception err) {
Log.e(err);
}
}
}
}, Display.GALLERY_VIDEO);
}
});
_findButton.setText("");
getIconContainer().add(_findButton);
getIconContainer().revalidate();
getIconContainer().repaint();
getLabelContainer().repaint();
this.revalidate();
}
public void render(boolean editing) {
if (isEditing) {
renderEdit();
}
if (!isEditing) {
renderSummary();
}
}
}
`
What am I doing wrong or show me working code sample to achieve what I am trying to achieve.

Compile error with two different fragmenttransaction types

I'm using AIDE on my phone, and trying to open a fragment from the navigation drawer in-app, but I get this error when I try to build the app:
An instance of type 'android.app.fragmenttransaction' cannot be assigned to a variable of type 'android.support.v4.app.fragmenttransaction'
Here is the code in the MainActivity.Java file:
package com.nickdgreen.net.act1;
import android.content.*;
import android.content.res.*;
import android.os.*;
import android.support.v4.app.*;
import android.support.v4.widget.*;
import android.view.*;
import android.widget.*;
import android.app.ActionBar.*;
import android.app.Activity.*;
import android.content.res.Configuration.*;
import android.os.Bundle.*;
import android.support.v4.app.ActionBarDrawerToggle.*;
import android.support.v4.app.Fragment.*;
import android.support.v4.app.FragmentActivity.*;
import android.support.v4.app.FragmentManager.*;
import android.support.v4.app.FragmentTransaction.*;
import android.support.v4.widget.DrawerLayout.*;
import android.view.Menu.*;
import android.view.MenuInflater.*;
import android.view.MenuItem.*;
import android.view.View.*;
import android.widget.AdapterView.*;
import android.widget.ArrayAdapter.*;
import android.widget.ListView.*;
public class MainActivity extends FragmentActivity
{
private ActionBarDrawerToggle drawerToggle;
final String fragments[] = {
"com.nickdgreen.net.act1.MainFragment",
"com.nickdgreen.net.act1.OneFragment",
"com.nickdgreen.net.act1.TwoFragment",
"com.nickdgreen.net.act1.ThreeFragment",
};
final String menuEntries[] = {
"Main", "One", "Two", "Three"
};
public MainActivity()
{
}
public void onConfigurationChanged(Configuration configuration)
{
super.onConfigurationChanged(configuration);
drawerToggle.onConfigurationChanged(configuration);
}
protected void onCreate(Bundle bundle)
{
super.onCreate(bundle);
setContentView(0x7f030000);
ArrayAdapter arrayadapter = new ArrayAdapter(getActionBar().getThemedContext(), 0x1090003, menuEntries);
final DrawerLayout drawer = (DrawerLayout)findViewById(0x7f080000);
final ListView navList = (ListView)findViewById(0x7f080002);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
drawerToggle = new ActionBarDrawerToggle(this, drawer, 0x7f020000, 0x7f050003, 0x7f050002) {
final MainActivity this$0;
public void onDrawerClosed(View view)
{
}
public void onDrawerOpened(View view)
{
}
{
this$0 = MainActivity.this;
}
};
drawer.setDrawerListener(drawerToggle);
navList.setAdapter(arrayadapter);
navList.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
final MainActivity this$0;
final DrawerLayout val$drawer;
final ListView val$navList;
public void onItemClick(AdapterView adapterview, View view, int i, long l)
{ {
}
drawer.closeDrawer(navList);
}
{
}
});
FragmentTransaction fragmenttransaction = getSupportFragmentManager().beginTransaction();
fragmenttransaction.replace(0x7f080001, Fragment.instantiate(this, fragments[0]));
fragmenttransaction.commit();
}
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(0x7f070000, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem menuitem)
{
if (drawerToggle.onOptionsItemSelected(menuitem))
{
return true;
} else
{
return super.onOptionsItemSelected(menuitem);
}
}
protected void onPostCreate(Bundle bundle)
{
super.onPostCreate(bundle);
drawerToggle.syncState();}
private class DrawerItemClickListener
implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id)
{ selectItem(position); }
/** Swaps fragments in the main content view */
private void
selectItem(int position) {
//Fragment fragment = new PlanetFragment(); Bundle args = new Bundle(); // args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
Intent intent = new Intent(MainActivity.this, OneFragment.class); startActivity(intent); } }
public class
ProductListActivity extends MainActivity {
#Override
public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate main_menu.xml
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.mainMenuAbout:
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
return true;
case R.id.mainMenuExit:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override public void onClick(Bundle b) { super.onCreate(b); setContentView(R.layout.primary);}
public void
selectItem(int position) {
Fragment newFragment;
FragmentTransaction transaction = getFragmentManager().beginTransaction();
switch (position) {
case 0:
newFragment = new OneFragment();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null); transaction.commit();
break;
case 1:
newFragment = new TwoFragment();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case 2:
newFragment = new ThreeFragment();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
case 3:
newFragment = new FourFragment();
transaction.replace(R.id.content_frame, newFragment);
transaction.addToBackStack(null);
transaction.commit();
break;
}
//DrawerList.setItemChecked(position, true);
CharSequence[] ListTitles = null;
setTitle(ListTitles[position]);
View DrawerList = null;
}
}
}
import android.support.v4.app.FragmentTransaction.*;
This line means that you are using FragmentTransaction; note that you are using the support lib's version, not the system's.
However, later in the code, you are assigning the support lib's FragmentTransaction to the native FragmentTransaction. They are incompatible and thus won't work. (Actually, it's what the error message itself is telling you.)
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// ^^^ support lib's version ^^^ this code returns a native FragmentTransaction
You should instead get the support lib's fragment manager, which will return the support FragmentTransaction.

How to display specific data from a sqlite database in a listview with a condition like 'where'?

I made an application with an SQLite database. I want to show the data in a listview, but I don't want to show all the data from the database, but just some data. So, I want to add a condition. I only want to show the data where string 'dag' is 'maandag'.
Can anyone help me?
This is the code from my DatabaseHelper, where the database is created:
package com.persoonlijk.rooster.test2;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import java.util.ArrayList;
import java.util.List;
//A helper class to manage database creation and version management.
public class DataManipulator
{
//Database attributes
private static final String DATABASE_NAME = "mydatabase.db";
static final String TABLE_NAME = null;
private static final int DATABASE_VERSION = 12;
//Table attributes
public static final String KEY_ROWID = "id";
public static final String KEY_DAG = "dag";
public static final String KEY_UUR = "uur";
public static final String KEY_VAK = "vak";
public static final String KEY_LOKAAL = "lokaal";
private static Context context;
static SQLiteDatabase db;
private SQLiteStatement insertStmt;
private static final String INSERT = "insert into " + TABLE_NAME + " (dag,uur,vak,lokaal) values (?,?,?,?)";
public DataManipulator(Context context) {
DataManipulator.context = context;
OpenHelper openHelper = new OpenHelper(DataManipulator.context);
DataManipulator.db = openHelper.getWritableDatabase();
this.insertStmt = DataManipulator.db.compileStatement(INSERT);
}
public long insert(String dag,String uur,String vak,String lokaal) {
this.insertStmt.bindString(1, dag);
this.insertStmt.bindString(2, uur);
this.insertStmt.bindString(3, vak);
this.insertStmt.bindString(4, lokaal);
return this.insertStmt.executeInsert();
}
public void deleteAll() {
db.delete(TABLE_NAME, null, null);
}
public List<String[]> selectAll()
{
List<String[]> list = new ArrayList<String[]>();
Cursor cursor = db.query(TABLE_NAME, new String[] { "id","dag","uur","vak","lokaal" }, null, null, null, null, "dag asc");
int x=0;
if (cursor.moveToFirst()) {
do {
String[] b1=new String[]{cursor.getString(0),cursor.getString(1),cursor.getString(2),
cursor.getString(3),cursor.getString(4)};
list.add(b1);
x=x+1;
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
cursor.close();
return list;
}
public boolean delete(long id) {
return db.delete(TABLE_NAME, KEY_ROWID + "=" + id, null) > 0;
}
private static class OpenHelper extends SQLiteOpenHelper {
OpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY, dag TEXT, uur TEXT, vak TEXT, lokaal TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
}
This is the code from the Activity where I want to display the specific data. Right now, all the data from the database is displayed.
package com.persoonlijk.rooster.test2;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class RoosterMaandag extends ListActivity{
TextView selection;
public int idToModify;
DataManipulator dm;
List<String[]> list = new ArrayList<String[]>();
List<String[]> names2 =null ;
String[] stg1;
/** Called when the activity is first created. */
//zorgt voor het overzicht van de gegevens uit de database
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.rooster);
dm = new DataManipulator(this);
names2 = dm.selectAll();
stg1=new String[names2.size()];
int x=0;
String stg;
for (String[] dag : names2) {
stg = dag[1]+" - "+dag[2]+ " - "+dag[3]+" - "+dag[4];
stg1[x]=stg;
x++;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,stg1);
this.setListAdapter(adapter);
selection=(TextView)findViewById(R.id.selection);
}
//menuknoppen
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(Menu.NONE, 0, 0, "Voeg gegevens toe");
menu.add(Menu.NONE, 1, 1, "Verwijder gegevens");
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
startActivity(new Intent(this, SaveData.class));
return true;
case 1:
startActivity(new Intent(this, VerwijderData.class));
return true;
}
return false;
}
}
Please let me know when my question isn't clear enough. I really hope someone can help me!
I added this code in my DataManipulator.java:
public List<String[]> selectSome(String arg) {
String[] columns = new String[] { "id", "dag", "uur", "vak", "lokaal" };
String[] selectionArgs = {arg};
Cursor cursor = db.query(TABLE_NAME, columns, "dag = ?", selectionArgs, null, null, "dag asc");
List<String[]> list = new ArrayList<String[]>(cursor.getCount());
while (cursor.moveToNext()) {
String[] b1 = new String[] { cursor.getString(0),
cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4) };
list.add(b1);
}
cursor.close();
return list;
}
and this code in my RoosterMaandag.java:
public void onCreate(Bundle savedInstanceState){
....
dm.selectSome("maandag");
....
}
I don't know about android but for sql
try this
select data_to_print from table_name where REGEXP_LIKE(column_name_where_to_match,'dag$');
more info here http://docs.oracle.com/cd/B12037_01/server.101/b10759/ap_posix001.htm#i690819
Example:
SQL> select job_id from jobs where regexp_like(job_id,'N$');
JOB_ID
----------
MK_MAN
PU_MAN
SA_MAN
ST_MAN
you need a new method in your DataManipulator class:
public List<String[]> selectSome(String arg) {
String[] columns = new String[] { "id", "dag", "uur", "vak", "lokaal" };
String[] selectionArgs = {arg};
Cursor cursor = db.query(TABLE_NAME, columns, "dag = ?", selectionArgs, null, null, "dag asc");
List<String[]> list = new ArrayList<String[]>(cursor.getCount());
while (cursor.moveToNext()) {
String[] b1 = new String[] { cursor.getString(0),
cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4) };
list.add(b1);
}
cursor.close();
return list;
}
I'll say it again. consider using a CursorAdapter for these tasks.

Resources