I try to make my comboBox multiple selection
and this my code:
this multiSelectComboBox:
import java.util.List;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.ComponentEvent;
import com.extjs.gxt.ui.client.event.WindowEvent;
import com.extjs.gxt.ui.client.event.WindowListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.widget.CheckBoxListView;
import com.extjs.gxt.ui.client.widget.Dialog;
import com.extjs.gxt.ui.client.widget.form.TriggerField;
import com.extjs.gxt.ui.client.widget.layout.FillLayout;
import com.google.gwt.user.client.Element;
public class MultiSelectComboBox<D extends ModelData> extends TriggerField<String> {
private Dialog checkBoxListHolder;
private CheckBoxListView<D> listView;
private ListStore<D> store;
private String delimiter = ",";
private boolean readOnly;
public MultiSelectComboBox() {
store = new ListStore<D>();
listView = new CheckBoxListView<D>();
}
#Override
protected void onTriggerClick(ComponentEvent ce) {
super.onTriggerClick(ce);
checkBoxListHolder.setSize(getWidth(), 200);
listView.setWidth(getWidth());
checkBoxListHolder.setPosition(getAbsoluteLeft(),
getAbsoluteTop() + getHeight());
if(checkBoxListHolder.isVisible()) {
checkBoxListHolder.hide();
}
else {
checkBoxListHolder.show();
}
}
#Override
protected void onRender(Element target, int index) {
super.onRender(target, index);
checkBoxListHolder = new Dialog();
checkBoxListHolder.setClosable(false);
checkBoxListHolder.setHeaderVisible(false);
checkBoxListHolder.setFooter(false);
checkBoxListHolder.setFrame(false);
checkBoxListHolder.setResizable(false);
checkBoxListHolder.setAutoHide(false);
checkBoxListHolder.getButtonBar().setVisible(false);
checkBoxListHolder.setLayout(new FillLayout());
checkBoxListHolder.add(listView);
listView.setStore(store);
checkBoxListHolder.addWindowListener(new WindowListener(){
#Override
public void windowHide(WindowEvent we) {
setValue(parseCheckedValues(listView));
}
});
}
private String parseCheckedValues(CheckBoxListView<D> checkBoxView) {
StringBuffer buf = new StringBuffer();
if(checkBoxView != null) {
List<D> selected = checkBoxView.getChecked();
int index = 1, len = selected.size();
for(D c : selected) {
buf.append(c.get(listView.getDisplayProperty()));
if(index < len) {
buf.append(delimiter);
}
index++;
}
}
return buf.toString();
}
public CheckBoxListView<D> getListView() {
return listView;
}
public void setListView(CheckBoxListView<D> listView) {
this.listView = listView;
}
public ListStore<D> getStore() {
return store;
}
public void setStore(ListStore<D> store) {
this.store = store;
}
public String getDelimiter() {
return delimiter;
}
public void setDelimiter(String delimiter) {
this.delimiter = delimiter;
}
public boolean isReadOnly() {
return readOnly;
}
public void setReadOnly(boolean readOnly) {
this.readOnly = readOnly;
}
}
then use this class in my project:
// ...
ListStore<UserDTO> employeeList = getUsers();
MultiSelectComboBox<ModelData> multiUsers = new MultiSelectComboBox<ModelData>();
multiUsers.getListView().setDisplayProperty("label");
//multiUsers.setStore(employeeList);
multiUsers.getStore().add(getModelData());
multiUsers.setFieldLabel("Employee");
//multiUsers.setEditable(true);
//multiUsers.setMaxHeight(200);
simpleForm.add(multiUsers, formData);
// ...
private List<ModelData> getModelData() {
List<ModelData> list = new ArrayList<ModelData>();
List<NctrUserDTO> employees= employeeList.getModels();
for (int i=0; i<employeeList.getCount(); i++) {
ModelData data = new BaseModel();
data.set("label", employeeList.getAt(i).getName());
list.add(data);
}
return list;
}
but the comboBox appear empty or have not any values when i pass values from employeeList but when i tried with static string values this works fine, i dont know why this problem occur, any suggestion please ??
It sounds as if your looking for something like the option multiple select boxes, if so you can look up the source code on Github for pointers - or rather than re-inventing the wheel, just use that GwtBootstrap3 component
Related
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
I'm new to android programming and I have a problem in displaying data from firestore. I want to display the data in fragments in the navigation drawer. I found tutorials that display it on activities but nothing in fragments. Please help me with this.
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
DrawerLayout drawerLayout;
ActionBarDrawerToggle actionBarDrawerToggle;
NavigationView navigationView;
FragmentTransaction fragmentTransaction;
private boolean shouldLoadProductFragOnBackPress = false;
public static int navItemIndex = 0;
public FirebaseAuth mAuth;
FirebaseFirestore db = FirebaseFirestore.getInstance();
private void Load_Product_fragment() {
navItemIndex = 0;
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.maincontainer,new ProductFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle(R.string.Productfragment_Title);
drawerLayout.closeDrawers();
}
private void Load_Service_fragment(){
navItemIndex = 1;
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.maincontainer,new ServiceFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle(R.string.Servicefragmnet_Title);
drawerLayout.closeDrawers();
shouldLoadProductFragOnBackPress = true;
}
private void Load_Account_fragment(){
navItemIndex = 2;
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.maincontainer,new AccountFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle(R.string.Accountfragment_Title);
drawerLayout.closeDrawers();
shouldLoadProductFragOnBackPress = true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar=(Toolbar)findViewById(R.id.Toolbar_Layout);
setSupportActionBar(toolbar);
drawerLayout=(DrawerLayout) findViewById(R.id.Drawer_Layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,toolbar,R.string.drawer_open,R.string.drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
drawerLayout.openDrawer(Gravity.LEFT);
Load_Product_fragment();
navigationView= findViewById(R.id.Navigation_View);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId())
{
case R.id.Productsfragment_ND:
Load_Product_fragment();
item.setChecked(true);
break;
case R.id.Servicefragment_ND:
Load_Service_fragment();
item.setChecked(true);
break;
case R.id.Accountfragemnt_ND:
Load_Account_fragment();
item.setChecked(true);
break;
}
return false;
}
});
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawers();
return;
}
// This code loads home fragment when back key is pressed
// when user is in other fragment than home
if (shouldLoadProductFragOnBackPress) {
// checking if user is on other navigation menu
// rather than home
if (navItemIndex !=0) {
navItemIndex = 0;
shouldLoadProductFragOnBackPress = false;
Load_Product_fragment();
return;
}
}
super.onBackPressed();
}
#Override
protected void onPostCreate(#Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
actionBarDrawerToggle.syncState();
}
public void del(View view) {db.collection("products").document("test")
.delete()
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
}
This is my main-activity.It contains the requirements for a navigation drawer for 3 fragments.I have a Firestore database linked to the app. I need to display the contents of the database in these fragments.
Next i will show one fragment and the recyclerview adapter and view holder i have tried using.
I am not sure if it is the correct way to do it.Please help me with this
public class ProductFragment extends Fragment {
private static final String TAG = ProductFragment.class.getSimpleName();
private RecyclerView recipeRecyclerview;
private LinearLayoutManager linearLayoutManager;
private Product_adapter mAdapter;
private DatabaseReference mDatabaseRef;
private DatabaseReference childRef;
public ProductFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate (R.layout.fragment_product, container, false);
getActivity().setTitle(getString(R.string.Productfrag_title));
linearLayoutManager = new LinearLayoutManager(getActivity());
recipeRecyclerview = view.findViewById(R.id.List_recycleview);
recipeRecyclerview.setHasFixedSize(true);
mDatabaseRef = FirebaseDatabase.getInstance().getReference();
childRef = mDatabaseRef.child("recipes");
mAdapter = new Product_adapter(Product_response.class, R.layout.list_layout, View_holder.class, childRef, getContext());
recipeRecyclerview.setLayoutManager(linearLayoutManager);
recipeRecyclerview.setAdapter(mAdapter);
return view;
}
}
This is my products-fragment. I have tried to add the recycler view.
Adapter
public class Product_adapter extends RecyclerView.Adapter {
FirebaseFirestore db = FirebaseFirestore.getInstance();
private Context context;
Query query = db.collection("products");
FirestoreRecyclerOptions<Product_response> response = new FirestoreRecyclerOptions.Builder<Product_response>()
.setQuery(query, Product_response.class)
.build();
FirestoreRecyclerAdapter adapter = new FirestoreRecyclerAdapter<Product_response, View_holder>(response) {
#Override
protected void onBindViewHolder(View_holder holder, int position, Product_response model) {
}
#Override
public View_holder onCreateViewHolder(ViewGroup group, int i) {
// Create a new instance of the ViewHolder, in this case we are using a custom
// layout called R.layout.message for each item
View view = LayoutInflater.from(group.getContext())
.inflate(R.layout.list_layout, group, false);
return new View_holder(view);
}
};
public Product_adapter(Class<Product_response> product_responseClass, int list_layout, Class<View_holder> view_holderClass, DatabaseReference childRef, Context context) {
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
}
#Override
public int getItemCount() {
return 0;
}
}
View holder
public class View_holder extends RecyclerView.ViewHolder{
private static final String TAG = View_holder.class.getSimpleName();
public TextView main_text, subtext ;
public ImageView image;
public View_holder(View itemView) {
super(itemView);
main_text = (TextView)itemView.findViewById(R.id.List_maintext);
subtext = (TextView)itemView.findViewById(R.id.List_subtext);
image = (ImageView)itemView.findViewById(R.id.List_imageview);
}
}
Next i will show the response page where i used the getter and setter for the firebase
import com.google.firebase.firestore.IgnoreExtraProperties;
#IgnoreExtraProperties
public class Product_response {
private String Product;
private String Cost;
public Product_response() {
}
public Product_response(String Product, String Cost){
this.Product= Product;
this.Cost= Cost;
}
public String getProduct() {
return Product;
}
public void setProduct(String Product) {
this.Product = Product;
}
public String getCost(){
return Cost;
}
public void setCost(String Cost)
{
this.Cost = Cost;
}
}
This is how my database looks like. I need to display this products in my fragment
This is the github link of the app. Please help me complete this
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();
}
}
}
}
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.
Here is my problem. I would like to write a primitive MultiRenameTool (the rename part is not important yet).
You could browse the directories on the left side (JTree), and when you select one, you could see its content on the right side (JTable - just the files).
The problem is, that I can't figure out how to pass the the selected directory to the JTable's list.
I've used the code of Kirill Grouchnikov for the JTree and I slighty modified it.
import java.awt.BorderLayout;
import java.awt.Component;
import java.io.File;
import java.io.FileFilter;
import java.util.*;
import javax.swing.*;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.filechooser.FileSystemView;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
/**
* #author Kirill Grouchnikov
*/
public class FileTreePanel extends JPanel {
protected static FileSystemView fsv = FileSystemView.getFileSystemView();
private JTree tree;
//At first I was trying this - but it is wrong.
public static File current;
private static class FileTreeCellRenderer extends DefaultTreeCellRenderer {
private Map<String, Icon> iconCache = new HashMap<String, Icon>();
private Map<File, String> rootNameCache = new HashMap<File, String>();
#Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
FileTreeNode ftn = (FileTreeNode) value;
File file = ftn.file;
String filename = "";
if (file != null) {
if (ftn.isFileSystemRoot) {
filename = this.rootNameCache.get(file);
if (filename == null) {
filename = fsv.getSystemDisplayName(file);
this.rootNameCache.put(file, filename);
}
} else {
filename = file.getName();
}
}
JLabel result = (JLabel) super.getTreeCellRendererComponent(tree, filename, sel, expanded, leaf, row, hasFocus);
if (file != null) {
Icon icon = this.iconCache.get(filename);
if (icon == null) {
icon = fsv.getSystemIcon(file);
this.iconCache.put(filename, icon);
}
result.setIcon(icon);
}
return result;
}
}
private static class FileTreeNode implements TreeNode {
private File file;
private File[] children;
private TreeNode parent;
private boolean isFileSystemRoot;
public FileTreeNode(File file, boolean isFileSystemRoot, TreeNode parent) {
this.file = file;
this.isFileSystemRoot = isFileSystemRoot;
this.parent = parent;
this.children = this.file.listFiles(new FileFilter() {
//!Modification here - display only the directories
#Override
public boolean accept(File file) {
return file.isDirectory();
}
});
if (this.children == null) {
this.children = new File[0];
}
//obliviously wrong "solution" :(
current = file;
}
public FileTreeNode(File[] children) {
this.file = null;
this.parent = null;
this.children = children;
}
#Override
public Enumeration<?> children() {
final int elementCount = this.children.length;
return new Enumeration<File>() {
int count = 0;
#Override
public boolean hasMoreElements() {
return this.count < elementCount;
}
#Override
public File nextElement() {
if (this.count < elementCount) {
return FileTreeNode.this.children[this.count++];
}
throw new NoSuchElementException("Nincs több elem.");
}
};
}
#Override
public boolean getAllowsChildren() {
return true;
}
#Override
public TreeNode getChildAt(int childIndex) {
return new FileTreeNode(this.children[childIndex],
this.parent == null, this);
}
#Override
public int getChildCount() {
return this.children.length;
}
#Override
public int getIndex(TreeNode node) {
FileTreeNode ftn = (FileTreeNode) node;
for (int i = 0; i < this.children.length; i++) {
if (ftn.file.equals(this.children[i])) {
return i;
}
}
return -1;
}
#Override
public TreeNode getParent() {
return this.parent;
}
#Override
public boolean isLeaf() {
return (this.getChildCount() == 0);
}
}
public FileTreePanel() {
super();
this.setLayout(new BorderLayout());
File[] roots = File.listRoots();
FileTreeNode rootTreeNode = new FileTreeNode(roots);
this.tree = new JTree(rootTreeNode);
this.tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
this.tree.setCellRenderer(new FileTreeCellRenderer());
this.tree.setRootVisible(true);
this.tree.addTreeSelectionListener(new JTreeSelectionListener());
JScrollPane jsp = new JScrollPane(this.tree);
this.add(jsp, BorderLayout.CENTER);
}
private class JTreeSelectionListener implements TreeSelectionListener {
#Override
public void valueChanged(TreeSelectionEvent jtsl) {
TreePath o = jtsl.getPath();
System.out.println(o);
System.out.println(current);
SelectionList.listBuilder(current);
}
}
}
The most important part is at the end, at the TreeSelectionEvent. Here somehow I should be able to convert/make/cast a File from the actually selected Directory.
import java.awt.BorderLayout;
import java.awt.Color;
import java.io.File;
import java.io.FileFilter;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class SelectionList extends JPanel {
private static FilesData data;
private static JTable table;
public SelectionList() {
super();
data = new FilesData();
table = new JTable(data);
table.setFillsViewportHeight(true);
table.setShowGrid(true);
table.setGridColor(Color.BLACK);
JScrollPane jsp = new JScrollPane(table);
this.add(jsp, BorderLayout.CENTER);
}
public static void listBuilder(final File f) {
data.files.clear();
File[] fs = f.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return file.isFile();
}
});
if (fs != null) {
for (File m : fs) {
Files ujFile = new Files(m, m.isHidden(), Menu.checkAll.getState());
if (!m.isHidden() || Menu.hiddenFilesVisibility.getState()) {
data.files.add(ujFile);
}
}
}
table.repaint();
}
}
It is interesting because of the listBuilder function. I think it is enough information, but if you need my other classes too, I will upload it. I appreciate any help! Thank you all in avance. Anyone? :(
The following snippet shows how you may get the file from the path inside valueChanged:
public void valueChanged(TreeSelectionEvent jtsl) {
TreePath path = jtsl.getPath();
FileTreeNode filenode = (FileTreeNode) path.getLastPathComponent();
File file = filenode.file;
...
}