Related
hello guys i'm back again on a question conserning my final project.
i have made a googlemap app with navigation drawer using activity( no fragment). i think you know about that. then rather than using header and menu, i have use a layout where the header should be so that i can make there a listview to display events all of this is clear.
screenshot
MapActivity :
public class MapActivity extends AppCompatActivity implements OnMapReadyCallback {
private static final String TAG = "MapActivity";
DrawerLayout drawerLayout;
LinearLayout drawer_up;
FloatingActionsMenu mainfloating;
FloatingActionButton profile, evennement, historique,reglage,aidesupport;
ImageButton zoomin,zoomout,showtail,zoom_auto,showgeofence,maplayer,drawermenugroit,drawermenugauche;
ProgressDialog progressDialog;
private Dialog mDialog;
private GoogleMap map;
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'ą
RelativeLayout nodata_layout;
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;
ImageButton map_layer_icon;
private AsyncTask downloadingAsync;
#Bind(R.id.listevent)
ListView listevent;
#Bind(R.id.clearAllEvents)
Button clearAllEvents;
#Bind(R.id.list) ListView list;
#Bind(R.id.nodata_layout) RelativeLayout nodata_layout1;
private boolean isRefreshLoced = false;
ApiInterface.GetGeofencesResult geofencesResult;
ArrayList<PolygonWithName> polygonsWithDetails = new ArrayList<>();
float previousZoomLevel = 0;
Boolean isAllFabsVisible;
RelativeLayout content_layout;
//fin de declaration a garder en tete
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ButterKnife.bind(this);
setContentView(R.layout.activity_map);
//devices elements
deviceIdMarkers = new HashMap<>();
markerIdDevices = new HashMap<>();
deviceIdPolyline = new HashMap<>();
deviceIdLastLatLng = new HashMap<>();
final String api_key = (String) DataSaver.getInstance(MapActivity.this).load("api_key");
final EventsAdapter adapter = new EventsAdapter(this);
listevent.setAdapter(adapter);
//deviceIdSmallMarkerInfo = new HashMap<>();
//delaration des boutons pour le compte de floatingButton, etc...;
drawermenugroit = findViewById(R.id.drawermenudroit);
drawer_up = findViewById(R.id.drawerup);
drawermenugauche = findViewById(R.id.drawermenugauche);
drawerLayout = findViewById(R.id.drawer);
// profile = findViewById(R.id.profile);
mainfloating = findViewById(R.id.mainFloatingBtn);
evennement = findViewById(R.id.evennements);
historique = findViewById(R.id.historiques);
reglage = findViewById(R.id.reglages);
aidesupport = findViewById(R.id.aide_support);
zoomin = findViewById(R.id.zoom_in);
LinearLayout list_event = findViewById(R.id.list_event);
zoomout = findViewById(R.id.zoom_out);
showtail = findViewById(R.id.showtails);
zoom_auto = findViewById(R.id.autozoom);
listevent = (ListView) findViewById(R.id.listevent);
list = (ListView) findViewById(R.id.list);
showgeofence = findViewById(R.id.geofences);
maplayer = findViewById(R.id.map_layer);
map_layer_icon = (ImageButton) findViewById(R.id.map_layer);
//loading_bar = (ProgressBar) findViewById(R.id.loading_progBar);
content_layout = (RelativeLayout) findViewById(R.id.content_layout);
nodata_layout = (RelativeLayout) findViewById(R.id.nodata_layout);
//fin de declaration de boutons
//chargement des données
progressDialog = new ProgressDialog(this);
progressDialog = new ProgressDialog(MapActivity.this);
progressDialog.setMessage("En cours..."); // Setting Message
progressDialog.setTitle("Chargement de la carte"); // Setting Title
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // Progress Dialog Style Spinner
progressDialog.show(); // Display Progress Dialog
progressDialog.setCancelable(false);
new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
}
progressDialog.dismiss();
}
}).start();
// fni de chargement des données
//open drawer and load list data in drawer layout button
drawermenugauche.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openDrawer(drawerLayout);
API.getApiInterface(MapActivity.this).getEvents(api_key, getResources().getString(R.string.lang), 0, new Callback<ApiInterface.GetEventsResult>() {
#Override
public void success(ApiInterface.GetEventsResult result, Response response) {
adapter.setArray(result.items.data);
if(result.items.data.size() != 0)
listevent.setVisibility(View.VISIBLE);
else
nodata_layout1.setVisibility(View.VISIBLE);
listevent.setVisibility(View.GONE);
}
#Override
public void failure(RetrofitError retrofitError) {
Toast.makeText(MapActivity.this, R.string.errorHappened, Toast.LENGTH_SHORT).show();
}
});
}
});
drawer_up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
closeDrawer(drawerLayout);
}
});
zoomin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
map.animateCamera(CameraUpdateFactory.zoomIn());
}
});
zoomout.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
map.animateCamera(CameraUpdateFactory.zoomOut());
}
});
zoom_auto.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
isAutoZoomEnabled = !isAutoZoomEnabled;
if (isAutoZoomEnabled)
{
zoom_auto.setImageResource(R.drawable.icon2022);
Toast.makeText(MapActivity.this, "Zoom Auto Activé", Toast.LENGTH_SHORT).show();
} else
{
zoom_auto.setImageResource(R.drawable.disableicon2022);
Toast.makeText(MapActivity.this, "Zoom Auto Désactivé", Toast.LENGTH_SHORT).show();
}
}
});
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
// ouverture et fermeture de drawer
private static void openDrawer(DrawerLayout drawerLayout){
drawerLayout.openDrawer(GravityCompat.START);
}
private static void closeDrawer(DrawerLayout drawerLayout){
if(drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}
}
//fin ouverture et fermeture drawer
......etc...
see my EventsAdapter code below:
public class EventsAdapter extends AwesomeAdapter<Event> {
public EventsAdapter(Context context) {
super(context);
}
ArrayList<Event> original;
#Override
public void setArray(ArrayList<Event> array) {
super.setArray(array);
if(original == null)
original = array;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null)
convertView = getLayoutInflater().inflate(R.layout.adapter_events, null);
Event item = getItem(position);
TextView device_name = (TextView) convertView.findViewById(R.id.device_name);
device_name.setText(item.device_name);
TextView date = (TextView) convertView.findViewById(R.id.date);
date.setText(item.time);
TextView message = (TextView) convertView.findViewById(R.id.message);
message.setText(item.message);
TextView geofence_name = (TextView) convertView.findViewById(R.id.geofence_name);
geofence_name.setText(item.geofence_name);
return convertView;
}
ItemFilter mFilter = new ItemFilter();
public Filter getFilter() {
return mFilter;
}
private class ItemFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint)
{
String filterString = constraint.toString().toLowerCase();
FilterResults results = new FilterResults();
final ArrayList<Event> nlist = new ArrayList<>();
for(Event item : original)
{
if(item.fitForFilter(filterString))
nlist.add(item);
}
results.values = nlist;
results.count = nlist.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
setArray((ArrayList<Event>) results.values);
notifyDataSetChanged();
}
}
}
then in my adapter_event layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:background="#color/whitesplash"
android:layout_marginBottom="10dp"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/instance"
android:layout_width="16dp"
android:layout_height="22dp"
android:src="#drawable/custom_floating_button" />
<TextView
android:id="#+id/device_nam"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/instance"
android:fontFamily="#font/fjallaoneregular"
android:text="Info Balise"
android:textColor="#color/black"
android:textSize="8dp"
android:textStyle="normal" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_below="#+id/device_nam"
android:outlineAmbientShadowColor="#color/blue" />
<TextView
android:id="#+id/device_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/device_nam"
android:layout_marginStart="16dp"
android:fontFamily="#font/fjallaoneregular"
android:text="device name"
android:textColor="#color/blue"
android:textSize="8dp"
android:textStyle="italic" />
<TextView
android:id="#+id/textspeed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="3dp"
android:layout_toEndOf="#+id/device_nam"
android:fontFamily="#font/fjallaoneregular"
android:text="Vitesse"
android:textColor="#color/black"
android:textSize="8dp"
android:textStyle="italic" />
<TextView
android:id="#+id/speed"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textspeed"
android:layout_marginStart="3dp"
android:layout_toEndOf="#+id/device_name"
android:fontFamily="#font/fjallaoneregular"
android:text="speed"
android:textColor="#color/blue"
android:textSize="8dp"
android:textStyle="italic" />
<TextView
android:id="#+id/message1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="3dp"
android:layout_toRightOf="#+id/textspeed"
android:fontFamily="#font/fjallaoneregular"
android:text="message"
android:textColor="#color/black"
android:textSize="8dp"
android:textStyle="normal" />
<TextView
android:id="#+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textspeed"
android:layout_marginStart="3dp"
android:layout_toEndOf="#+id/speed"
android:fontFamily="#font/fjallaoneregular"
android:text="massage"
android:textColor="#color/blue"
android:textSize="8sp"
android:textStyle="italic" />
<View
android:id="#+id/view2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/device_name" />
<TextView
android:id="#+id/datetext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/device_name"
android:layout_toEndOf="#+id/instance"
android:fontFamily="#font/fjallaoneregular"
android:text="date:"
android:textColor="#color/black"
android:textSize="8dp"
android:textStyle="normal" />
<TextView
android:id="#+id/date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/device_name"
android:layout_marginStart="3dp"
android:layout_toEndOf="#+id/datetext"
android:fontFamily="#font/fjallaoneregular"
android:text="date"
android:textColor="#color/blue"
android:textSize="8sp"
android:textStyle="italic" />
<TextView
android:id="#+id/geofence_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="geofence_name"
android:fontFamily="#font/lobsterregular"
android:layout_below="#+id/date"
android:layout_marginStart="3dp"
android:layout_toRightOf="#+id/instance"
android:textSize="8dp"
android:textColor="#color/blue"/>
</RelativeLayout>
in this adpater_events i have found no mistake. and in the drawer_tracesas i said before( i am not using menu and header in navigationDrawer i would like to use a layout that i called drawer_traces) like below
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/drawerup"
android:orientation="horizontal"
android:background="#color/blue">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/objects"
android:src="#drawable/ic_menu_24"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="16sp"
android:text="#string/objects" />
</LinearLayout>
<TextView
android:id="#+id/Liste_Balises"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/drawerup"
android:fontFamily="#font/fjallaoneregular"
android:gravity="center"
android:text="#string/liste_balises"
android:textColor="#color/blue" />
<LinearLayout
android:id="#+id/list_balises"
android:layout_width="match_parent"
android:layout_height="300dp"
android:orientation="vertical"
android:layout_below="#+id/Liste_Balises"
android:layout_marginTop="10dp"
android:minHeight="?android:attr/listPreferredItemHeight">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:orientation="vertical" />
</LinearLayout>
<TextView
android:id="#+id/list_events"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/list_balises"
android:layout_marginTop="10dp"
android:fontFamily="#font/fjallaoneregular"
android:gravity="center"
android:text="#string/liste_evennemT"
android:textColor="#color/blue" />
<LinearLayout
android:id="#+id/list_event"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_below="#+id/list_events"
android:layout_marginTop="10dp"
android:minHeight="?android:attr/listPreferredItemHeight">
<ListView
android:id="#+id/listevent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:orientation="vertical" />
</LinearLayout>
<RelativeLayout
android:id="#+id/nodata_layout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/list_event"
android:layout_above="#+id/clearAllEvents"
android:background="#ffffff"
android:visibility="gone"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/noEventsData"/>
</RelativeLayout>
<Button
android:id="#+id/clearAllEvents"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/list_event"
android:fontFamily="#font/fjallaoneregular"
android:text="Effacer Evennements"/>
</RelativeLayout>
this layout (drawer_trace) will be displayed in mapActivity as a navigation Drawer. we are ok for that.
and then i have my Events Model:
public class Event
{
public int id, user_id, device_id, position_id, alert_id;
// geofence_id
public String message;
public String address;
public float altitude;
// course
public float latitude, longitude;
// power
public float speed;
public String time;
// deleted
public String device_name, geofence_name;
public boolean fitForFilter(String filterString) {
if(message.toLowerCase().contains(filterString.toLowerCase()))
return true;
if(address.toLowerCase().contains(filterString.toLowerCase()))
return true;
if(time.toLowerCase().contains(filterString.toLowerCase()))
return true;
if(device_name.toLowerCase().contains(filterString.toLowerCase()))
return true;
if(geofence_name.toLowerCase().contains(filterString.toLowerCase()))
return true;
return false;
}
i am using REST API in backend and retrofit.
everything is ok untill i try to eun the app.
it says ERROR MESSAGE:
Process: com.gabontech.gprstest, PID: 14460
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gabontech.gprstest/com.gabontech.gprstest.activities.MapActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3433)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3572)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:140)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:96)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2097)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:264)
at android.app.ActivityThread.main(ActivityThread.java:7663)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.gabontech.gprstest.activities.MapActivity.onCreate(MapActivity.java:139)
at android.app.Activity.performCreate(Activity.java:7805)
at android.app.Activity.performCreate(Activity.java:7794)
i think about the adapter where in EventsAdapter.class line ref:::::
convertView = getLayoutInflater().inflate(R.layout.adapter_events, null);
ihave spent two days there. please if you can help it will give me a hand for my exam. Thank so much guys
I have written code to list contacts in recycler view. But it doesn't display value in recycler view. The code is given below.
HomeActivity.java
private DatabaseReference mDatabase;
private RecyclerView PList;
private FirebaseRecyclerAdapter<project, ProjViewHolder> FBRA;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
PList = findViewById(R.id.ProjList);
PList.setHasFixedSize(true);
PList.setLayoutManager(new LinearLayoutManager(this));
mDatabase = FirebaseDatabase.getInstance().getReference().child("Contacts");
}
#Override
protected void onStart() {
super.onStart();
FirebaseRecyclerOptions<project> options = new FirebaseRecyclerOptions.Builder<project>().setQuery(mDatabase, project.class).build();
FBRA = new FirebaseRecyclerAdapter<project, ProjViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull ProjViewHolder holder, int position, #NonNull project model) {
String proj_key = getRef(position).getKey();
holder.cpname.setText(model.getCname());
holder.cplocation.setText(model.getCcity());
holder.ccname.setText(model.getPcontact());
holder.ccdesig.setText(model.getPdesig());
}
#Override
public ProjViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.proj_row, parent, false);
return new ProjViewHolder(view);
}
};
PList.setAdapter(FBRA);
FBRA.startListening();
}
public class ProjViewHolder extends RecyclerView.ViewHolder {
TextView cpname, cplocation, ccname, ccdesig;
ProjViewHolder(#NonNull View itemView) {
super(itemView);
cpname = itemView.findViewById(R.id.FCName);
cplocation = itemView.findViewById(R.id.FCLocation);
ccname = itemView.findViewById(R.id.FPName);
ccdesig = itemView.findViewById(R.id.FPDesig);
}
}
#Override
protected void onStop() {
super.onStop();
FBRA.stopListening();
}
FormActivity.java
public class FormActivity extends AppCompatActivity {
private EditText CName, PContact,PDesig, CCity;
private FirebaseDatabase mDatabase;
private Button Fbtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
CName = findViewById(R.id.CompName);
PContact = findViewById(R.id.PContact);
PDesig = findViewById(R.id.PDesig);
CCity = findViewById(R.id.CCity);
mDatabase = FirebaseDatabase.getInstance();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.save, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
String dCName = CName.getText().toString().trim();
String dPContact = PContact.getText().toString().trim();
String dPDesig = PDesig.getText().toString().trim();
String dCCity = CCity.getText().toString().trim();
String name = CName.getText().toString().trim();
DatabaseReference mDbRef = mDatabase.getReference().child("Contacts").child(name).push();
mDbRef.child("cname").setValue(dCName);
mDbRef.child("pcontact").setValue(dPContact);
mDbRef.child("pdesig").setValue(dPDesig);
mDbRef.child("ccity").setValue(dCCity);
Toast.makeText(FormActivity.this, "Contact Submitted Successfully", Toast.LENGTH_LONG).show();
Intent intent = new Intent(FormActivity.this, HomeActivity.class);
startActivity(intent);
finish();
}
}
return super.onOptionsItemSelected(item);
}
}
Project.class
public class project {
String cname, pcontact, pdesig, ccity;
public project(){
}
public project(String cname, String pcontact, String pdesig, String ccity) {
this.cname = cname;
this.pcontact = pcontact;
this.pdesig = pdesig;
this.ccity = ccity;
}
public String getCname() {
return cname;
}
public void setCname(String cname) {
this.cname = cname;
}
public String getPcontact() {
return pcontact;
}
public void setPcontact(String pcontact) {
this.pcontact = pcontact;
}
public String getPdesig() {
return pdesig;
}
public void setPdesig(String pdesig) {
this.pdesig = pdesig;
}
public String getCcity() {
return ccity;
}
public void setCcity(String ccity) {
this.ccity = ccity;
}
}
HomeActivity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".HomeActivity">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="5dp"
android:id="#+id/ProjList"
/>
</RelativeLayout>
ProjRow.xml
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_margin="2dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/FCName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAllCaps="true"
android:elegantTextHeight="true"
android:textColor="#color/colorBlue"
android:maxLength="25"
android:paddingTop="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:textSize="16dp"
android:textStyle="bold"
android:layout_marginTop="10dp"
/>
<TextView
android:id="#+id/FCLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:layout_alignParentRight="true"
android:textAllCaps="true"
android:elegantTextHeight="true"
android:textColor="#color/colorDark"
android:layout_marginTop="13dp"
android:paddingTop="5dp"
android:textSize="14dp"
/>
<TextView
android:id="#+id/FPName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/FCName"
android:layout_alignParentLeft="true"
android:elegantTextHeight="true"
android:textStyle="bold"
android:textColor="#color/colorText"
android:paddingTop="5dp"
android:paddingRight="3dp"
android:layout_marginTop="10dp"
android:layout_marginLeft="10dp"
android:textSize="15dp"
/>
<TextView
android:id="#+id/FPDesig"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/FCName"
android:layout_alignParentRight="true"
android:layout_marginTop="10dp"
android:layout_marginRight="5dp"
android:padding="5dp"
android:textSize="14dp"
android:textColor="#color/colorNext"
android:elegantTextHeight="true"
/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
the code is working fine without error. But the intended value is not captured from database. If push() is removed from DatabaseReference mDbRef = mDatabase.getReference().child("Contacts").child(name).push(); , it works absolutely fine. but it overwrites on existing data while adding new data for the same 'name'. After adding push, the data are getting stored in sub child record. Please guide me how to refer and get back the data in recycleview adapter.
The each record stored under 'Contacts' before adding push()but overwrites when added a person for the same company.
After adding push() each record stored under company name with unique key.
I'm trying to make working CheckBox inside ListView.
Layout is just main.xml which shows multiple row.xml when new information is added to sqlite database.
I can make working CheckBox in main.xml, but I don't know how to make working CheckBox inside row.xml.
AndroidSQLite.java (shows main.xml, and row.xml inside it)
public class AndroidSQLite extends Activity {
(...)
checkBoxMain = (CheckBox)findViewById(R.id.checkboxmain1);
listContent = (ListView)findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
cursor = mySQLiteAdapter.queueAll();
String[] from = new String[]{SQLiteAdapter._id,
SQLiteAdapter.KEY_NAME,
SQLiteAdapter.KEY_QUANTITY,
SQLiteAdapter.KEY_CHECKED};
int[] to = new int[]{R.id.id, R.id.name, R.id.quantity,
R.id.checkboxmain};
cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from,
to);
listContent.setAdapter(cursorAdapter);
listContent.setOnItemClickListener(listContentOnItemClickListener);
buttonAdd.setOnClickListener(buttonAddOnClickListener);
checkBoxMain.setOnClickListener(onCheckboxClicked);
}
CheckBox OnClickListener (AndroidSQLite.java)
CheckBox.OnClickListener onCheckboxClicked
= new CheckBox.OnClickListener() {
public void onClick(View v) {
CheckBox checkBoxMain = (CheckBox)
findViewById(R.id.checkboxmain1);
boolean checked = checkBoxMain.isChecked();
if (checked) {
Boolean data1 = checkBoxMain.isChecked();
mySQLiteAdapter.insertChecked(data1);
updateList();
}
}
};
ListView OnItemClickListener (AndroidSQLite.java)
private ListView.OnItemClickListener listContentOnItemClickListener
= new ListView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position,
long id) {
Cursor cursor = (Cursor) parent.getItemAtPosition(position);
final int item_id =
cursor.getInt(cursor.getColumnIndex(SQLiteAdapter._id));
String item_name =
cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_NAME));
String item_quantity =
cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_QUANTITY));
AlertDialog.Builder myDialog
= new AlertDialog.Builder(AndroidSQLite.this);
// when item in row.xml is clicked alertdialog is shown
// code of AlertDialog
myDialog.show();
}};
onDestroy and updateList() (AndroidSQLite.java)
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mySQLiteAdapter.close();
}
private void updateList(){
cursor.requery();
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="#+id/panelup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LIST SQ1"
/>
<ListView
android:id="#+id/contentlist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/panelup"
android:layout_above="#id/paneldown"/>
<CheckBox
android:id="#+id/checkboxmain1"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/paneldown"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<EditText
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
<EditText
android:id="#+id/quantity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
/>
<Spinner
android:id="#+id/mu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/mu_values"
android:layout_weight="2"
/>
<Button
android:id="#+id/add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="+"
/>
</LinearLayout>
</RelativeLayout>
row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/layoutmain"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:padding="2dip"
android:text="M"/>
<TextView
android:id="#+id/id"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:padding="2dip"
android:paddingRight="10dip"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:padding="2dip"
android:paddingRight="10dip"
android:text="-" />
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="2dip"/>
</LinearLayout>
<TextView
android:id="#+id/quantity"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="2dip"/>
<CheckBox
android:id="#+id/checkboxmain2"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
(checkboxmain2 from row.xml have android:focusable and android:focusableInTouchMode set on "false" because if it's not false, ListView OnItemClickListener it's notr working)
SQLiteAdapter.java
public class SQLiteAdapter {
(...)
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close(){
sqLiteHelper.close();
}
public long insertChecked(boolean data1){
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_CHECKED, data1);
return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);
}
public Cursor queueAll(){
String[] columns = new String[]{_id, KEY_NAME, KEY_PRICE,
KEY_QUANTITY, KEY_MU,
KEY_PDATE, KEY_SHOP, KEY_CHECKED};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null, null, null, null, null);
return cursor;
}
screen
CheckBox on top, which is checked on screen is working CheckBox (checkboxmain1) which adds "1" to database
Is there any way to make response of CheckBoxes in ListView?
The following is a relatively simple way of handling click events of views within an Item of a ListView.
To simply obtain the actual item that has been clicked to distinguish it from another Item you need a Custom Adapter, in this case a Custom Cursor Adapter, in which you can set the view's tag to an appropriate value (the id).
In conjunction with this you use the onClick attribute to specify the method to be called when the view (checkbox) is clicked, which is defined in the Activity.
The following is a working example based upon your code. It uses a simpler and more flexible method for managing the ListView i.e. manageListView
Note some of your code has been omitted (commented out) for convenience.
The Code
row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/layoutmain"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:padding="2dip"
android:text="M"/>
<TextView
android:id="#+id/id"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:padding="2dip"
android:paddingRight="10dip"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:padding="2dip"
android:paddingRight="10dip"
android:text="-" />
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="2dip"/>
</LinearLayout>
<TextView
android:id="#+id/quantity"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="2dip"/>
<CheckBox
android:id="#+id/checkboxmain2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="ListViewCheckBoxHanlder"/>
</LinearLayout>
Note the changes made to the CheckBox
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="#+id/panelup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="LIST SQ1"
/>
<ListView
android:id="#+id/contentlist"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/panelup"
android:layout_above="#id/paneldown"/>
<CheckBox
android:id="#+id/checkboxmain1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/paneldown"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true">
<EditText
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
/>
<EditText
android:id="#+id/quantity"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
/>
<Spinner
android:id="#+id/mu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:entries="#array/mu_values"
android:layout_weight="2"
/>
<Button
android:id="#+id/add"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:text="+"
/>
</LinearLayout>
</RelativeLayout>
AndroidSQLite.java
public class AndroidSQLite extends AppCompatActivity {
CheckBox checkBoxMain;
ListView listContent;
Button buttonAdd;
Cursor cursor;
SQLiteAdapter mySQLiteAdapter;
//SimpleCursorAdapter cursorAdapter; //<<<<<<<<<< NOT USED ANYMORE
MyCursorAdapter myadapter; //<<<<<<<<<< Use a custom adapter that sets the tag of the checkbox to the respective id
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkBoxMain = (CheckBox)findViewById(R.id.checkboxmain1);
listContent = (ListView)findViewById(R.id.contentlist);
mySQLiteAdapter = new SQLiteAdapter(this);
mySQLiteAdapter.openToWrite();
manageListView(); //<<<<<<<<<< ADDED
/* !!!!!!!!! COMMENTED OUT
cursor = mySQLiteAdapter.queueAll();
String[] from = new String[]{SQLiteAdapter._id,
SQLiteAdapter.KEY_NAME,
SQLiteAdapter.KEY_QUANTITY,
SQLiteAdapter.KEY_CHECKED};
int[] to = new int[]{R.id.id, R.id.name, R.id.quantity,
R.id.checkboxmain2};
cursorAdapter =
new SimpleCursorAdapter(this, R.layout.row, cursor, from,
to,0);
listContent.setAdapter(cursorAdapter);
listContent.setOnItemClickListener(listContentOnItemClickListener);
*/
//buttonAdd.setOnClickListener(buttonAddOnClickListener); //<<<<<<<<<<< you want this back in
}
//<<<<<<<<<< ADDED >>>>>>>>>>
#Override
protected void onResume() {
super.onResume();
manageListView(); //Refresh the List when resuming e.g. returning from another activity
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
cursor.close(); //<<<<<<<<<< SHOULD ALWAYS CLOSE CURSOR
mySQLiteAdapter.close();
}
//<<<<<<<<<< NO LONGER USED >>>>>>>>>>
private void updateList(){
cursor = mySQLiteAdapter.queueAll();
myadapter.swapCursor(cursor);
}
//<<<<<<<< NOTE NOT USED but you'd want this to be used
CheckBox.OnClickListener onCheckboxClicked
= new CheckBox.OnClickListener() {
public void onClick(View v) {
CheckBox checkBoxMain = (CheckBox)
findViewById(R.id.checkboxmain1);
boolean checked = checkBoxMain.isChecked();
if (checked) {
Boolean data1 = checkBoxMain.isChecked();
mySQLiteAdapter.insertChecked(data1);
manageListView(); //<<<<<<<<<< refresh the ListView
}
}
};
//<<<<<<<<<<NOT USED>>>>>>>>>>
private ListView.OnItemClickListener listContentOnItemClickListener
= new ListView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int
position,
long id) {
Cursor cursor = (Cursor) parent.getItemAtPosition(position);
final int item_id =
cursor.getInt(cursor.getColumnIndex(SQLiteAdapter._id));
String item_name =
cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_NAME));
String item_quantity =
cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_QUANTITY));
AlertDialog.Builder myDialog
= new AlertDialog.Builder(AndroidSQLite.this);
// when item in row.xml is clicked alertdialog is shown
// code of AlertDialog
myDialog.show();
updateList();
}
};
/**<<<<<<<<<< ADDED >>>>>>>>>>>
* Manage the ListView building from new or refreshing the data
*/
private void manageListView() {
cursor = mySQLiteAdapter.queueAll(); // get the source data (cursor) for the listview
if (myadapter == null) {
myadapter = new MyCursorAdapter(this,cursor);
listContent.setAdapter(myadapter);
} else {
myadapter.swapCursor(cursor);
}
}
/**<<<<<<<<<< ADDED >>>>>>>>>>
* Handle the CheckBox being clicked,
* NOTE set in the layout
* #param v The View
*/
public void ListViewCheckBoxHanlder(View v) {
CheckBox cb = v.findViewById(R.id.checkboxmain2);
Toast.makeText(this, "You clicked the CheckBox for ID " + (String) cb.getTag(), Toast.LENGTH_SHORT).show();
int checked = 0;
if (cb.isChecked()) {
checked = 1;
}
long id = Long.valueOf((String) cb.getTag());
mySQLiteAdapter.updateChecked(id,checked);
manageListView();
}
}
Note some code commented out has been replaced, some has been commented out for convenience.
MyCursorAdapter.java
public class MyCursorAdapter extends CursorAdapter {
public MyCursorAdapter(Context context, Cursor c) {
super(context, c, true);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);
return v;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.row,parent,false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
//Note Cursor will be positioned appropriately
TextView name = (TextView) view.findViewById(R.id.name);
TextView id = (TextView) view.findViewById(R.id.id);
TextView quantity = (TextView) view.findViewById(R.id.quantity);
CheckBox cb = (CheckBox) view.findViewById(R.id.checkboxmain2);
name.setText(cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_NAME)));
id.setText(cursor.getString(cursor.getColumnIndex(SQLiteAdapter._id)));
quantity.setText(cursor.getString(cursor.getColumnIndex(SQLiteAdapter.KEY_QUANTITY)));
cb.setChecked(cursor.getInt(cursor.getColumnIndex(SQLiteAdapter.KEY_CHECKED)) > 0);
cb.setTag(cursor.getString(cursor.getColumnIndex(SQLiteAdapter._id))); //<<<<<<<<<< SET TAG to the ID
}
}
Note the above is a new class.
SQliteAdapter.java
public class SQLiteAdapter {
SQLiteDatabase sqLiteDatabase;
SQLiteHelper sqLiteHelper;
Context context;
public static final String KEY_CHECKED = "checked";
public static final String _id = BaseColumns._ID;
public static final String KEY_NAME = "name";
public static final String KEY_QUANTITY = "quantity";
public static final String KEY_PRICE = "price";
public static final String KEY_MU = "mu";
public static final String KEY_PDATE = "pdate";
public static final String KEY_SHOP = "shop";
public SQLiteAdapter(Context context) {
this.context = context;
openToWrite();
}
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close() {
sqLiteHelper.close();
}
public long insertChecked(boolean data1) {
ContentValues contentValues = new ContentValues();
contentValues.put(KEY_CHECKED, data1);
return sqLiteDatabase.insert(MYDATABASE_TABLE, null, contentValues);
}
public int updateChecked(long id,int check) {
ContentValues cv = new ContentValues();
cv.put(KEY_CHECKED,check);
String whereclause = _id + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
return sqLiteDatabase.update(MYDATABASE_TABLE,cv,whereclause,whereargs);
}
public Cursor queueAll() {
String[] columns = new String[]{_id, KEY_NAME, KEY_PRICE,
KEY_QUANTITY, KEY_MU,
KEY_PDATE, KEY_SHOP, KEY_CHECKED};
Cursor cursor = sqLiteDatabase.query(MYDATABASE_TABLE, columns,
null, null, null, null, null);
return cursor;
}
}
Note this may well be different, it was created to cater for testing.
SQLiteHelper.java
public class SQLiteHelper extends SQLiteOpenHelper {
public static final String MYDATABASE_NAME = "mydatabase";
public static final int MYDATABASE_VERSION = 1;
public static final String MYDATABASE_TABLE = "mytable";
SQLiteDatabase mDB;
public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,int version) {
super(context, name, factory, version);
mDB = this.getWritableDatabase();
}
#Override
public void onCreate(SQLiteDatabase db) {
String crt_tbl_sql = "CREATE TABLE IF NOT EXISTS " + MYDATABASE_TABLE + "(" +
SQLiteAdapter._id + " INTEGER PRIMARY KEY, " +
SQLiteAdapter.KEY_NAME + " TEXT, " +
SQLiteAdapter.KEY_SHOP + " TEXT, " +
SQLiteAdapter.KEY_PDATE + " TEXT, " +
SQLiteAdapter.KEY_PRICE + " REAL, " +
SQLiteAdapter.KEY_QUANTITY + " INTEGER, " +
SQLiteAdapter.KEY_MU + " TEXT, " +
SQLiteAdapter.KEY_CHECKED + " INTEGER DEFAULT 0" +
")";
db.execSQL(crt_tbl_sql);
addSomeTestingData(db,10);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
private long addRow(String name, String shop, String pdate, double price, int quantity, String mu, SQLiteDatabase db) {
ContentValues cv = new ContentValues();
cv.put(SQLiteAdapter.KEY_NAME,name);
cv.put(SQLiteAdapter.KEY_SHOP,shop);
cv.put(SQLiteAdapter.KEY_PDATE,pdate);
cv.put(SQLiteAdapter.KEY_PRICE,price);
cv.put(SQLiteAdapter.KEY_QUANTITY,quantity);
cv.put(SQLiteAdapter.KEY_MU,mu);
return db.insert(MYDATABASE_TABLE,null,cv);
}
private void addSomeTestingData(SQLiteDatabase db, int number_to_add) {
for (int i = 0; i < number_to_add;i++) {
String suffix = String.valueOf(i);
String day_in_month = suffix;
if (i < 10) {
day_in_month = "0" + day_in_month;
}
addRow(
"Test" + suffix,
"Shop" + suffix,
"2019-01-" + day_in_month,
10.5 + new Double(i * 3),
i * 4,
"mu" + suffix,
db
);
}
}
}
Note this may well be different, it was created to cater for testing.
Result
The following is a screenshot taken after clicking a number of checkboxes so the Toast would be shown :-
And a screenshot after restarting the App (showing that the state has been retained i.e. database updated according to the checkboxes) :-
I am just parse some data and display on my ListProperty Class. I am using RecyclerView and CardView as a row layout. Somehow all is working fine i don't see any error in verbose. But the Data and row layout dosent display in my main activity. Activity is showing blank. I am trying from hours but kind find the error. Please someone help
My MainActivity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin">
<android.support.v7.widget.RecyclerView
android:id="#+id/cardList"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
This is row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imageViewFront" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_marginLeft="100dp"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="New Text"
android:textColor="#0055CC"
android:id="#+id/textViewPropertyname" />
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:textColor="#0055CC"
android:layout_columnWeight="1"
android:id="#+id/textViewPropertyDescription"/>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
This is myAdapter.java
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
List<Bean> DataList;
public MyAdapter(List<Bean> List){
super();
DataList = List;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView propertyName;
public TextView propertyDesc;
public ImageView ImageFront;
public MyViewHolder(View v) {
super(v);
propertyName = (TextView) v.findViewById(R.id.textViewPropertyname);
propertyDesc = (TextView) v.findViewById(R.id.textViewPropertyDescription);
ImageFront = (ImageView) v.findViewById(R.id.imageViewFront);
}
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).
inflate(R.layout.list_card_view,parent,false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyAdapter.MyViewHolder holder, int position) {
Bean bean = DataList.get(position);
holder.propertyName.setText(bean.getPropertyName());
holder.propertyDesc.setText(bean.getPropertyDescription());
holder.ImageFront.setImageResource(R.drawable.agriculture);
}
#Override
public int getItemCount() {
return DataList.size();
}
}
And this is my MainActivity.java
public class ListProperty extends AppCompatActivity {
private RecyclerView mRecyclerView;
private MyAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
Bean bean;
AQuery aQuery;
JSONObject jsonObject;
List<Bean> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_property);
aQuery= new AQuery(getApplicationContext());
String URL = "http://192.168.0.107/propertyapp/service/simpleservice.php";
list = new ArrayList<Bean>();
mRecyclerView = (RecyclerView) findViewById(R.id.cardList);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new MyAdapter(list);
mRecyclerView.setAdapter(mAdapter);
aQuery.ajax(URL, JSONObject.class,new AjaxCallback<JSONObject>(){
#Override
public void callback(String url, JSONObject object, AjaxStatus status) {
try {
bean = new Bean();
list = new ArrayList<Bean>();
String string = object.getString("data");
JSONArray jsonArray = new JSONArray(string);
for (int i=0;i<jsonArray.length();i++) {
jsonObject = jsonArray.getJSONObject(i);
bean.setPropertyName("property_name");
bean.setPropertyDescription("property_desc");
list.add(bean);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
Try to remove parent LinearLayout. Because you have CardView which is acting as list item.
Try this row.xml -
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/imageViewFront" />
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_marginLeft="100dp"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:text="New Text"
android:textColor="#0055CC"
android:id="#+id/textViewPropertyname" />
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:textColor="#0055CC"
android:layout_columnWeight="1"
android:id="#+id/textViewPropertyDescription"/>
</LinearLayout>
</android.support.v7.widget.CardView>
Hope it will help :)
Just add notifyDataSetChanged() to your Activity as below:
aQuery.ajax(URL, JSONObject.class,new AjaxCallback<JSONObject>(){
#Override
public void callback(String url, JSONObject object, AjaxStatus status) {
try {
bean = new Bean();
list = new ArrayList<Bean>();
String string = object.getString("data");
JSONArray jsonArray = new JSONArray(string);
for (int i=0;i<jsonArray.length();i++) {
jsonObject = jsonArray.getJSONObject(i);
bean.setPropertyName("property_name");
bean.setPropertyDescription("property_desc");
list.add(bean);
}
//here notify your adapter
//is to Notify any registered observers that the data set has changed.
mAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Because on your callback you have created new instance of list
list = new ArrayList<Bean>();
then in fact, the new created list and DataList in your adapter are pointing to 2 difference objects => calling notifyDataSetChanged here won't work. Try writing method updateData on MyAdapter and call it from your callback method
public void updateData(List<Bean> List){
DataList = List;
notifyDataSetChanged();
}
On your callback:
aQuery.ajax(URL, JSONObject.class,new AjaxCallback<JSONObject>(){
#Override
public void callback(String url, JSONObject object, AjaxStatus status) {
try {
bean = new Bean();
list = new ArrayList<Bean>();
String string = object.getString("data");
JSONArray jsonArray = new JSONArray(string);
for (int i=0;i<jsonArray.length();i++) {
jsonObject = jsonArray.getJSONObject(i);
bean.setPropertyName("property_name");
bean.setPropertyDescription("property_desc");
list.add(bean);
}
// update data
mAdapter.updateData(list);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
im have a layout named type_of_dairy with below code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="20dp"
android:layoutDirection="rtl"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Type"
android:id="#+id/iceCreamType"
android:layout_gravity="center_horizontal"
android:layout_weight="0.05"
android:layout_marginTop="20dp"/>
<ListView
android:layout_width="match_parent"
android:layout_height="35dp"
android:id="#+id/listView"
android:layout_weight="0.26"
android:background="#999900"
android:choiceMode="singleChoice"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Flavour"
android:id="#+id/iceCreamFlavor"
android:layout_gravity="center_horizontal"
android:layout_weight="0.05"
android:layout_marginTop="10dp"/>
<ListView
android:layout_width="match_parent"
android:layout_height="58dp"
android:id="#+id/listView2"
android:layout_gravity="center_horizontal"
android:background="#999900"
android:choiceMode="singleChoice"
/>
<EditText
android:layout_width="89dp"
android:layout_height="wrap_content"
android:inputType="number"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:ems="10"
android:id="#+id/editText"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Apply"
android:id="#+id/countOficeCream"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:layout_weight="0.05" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cancel"
android:id="#+id/iceCreamReject"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:layout_weight="0.05" />
</LinearLayout>
as you see i have two ListView, i have filled out the first ListView from my DB, a field of a table of my DB has selected to fill in this ListView(#+id/listView) and there are two buttons,i want that as i selected an item from the first ListView(#+id/listView) , the second ListView (#+id/listView2) fill out with another field of my DB,
public class Dairy extends Activity {
Button returnBack;
Statement statement;
Statement statement2;
ListView dairyType;
ListView dairyFlavour;
ArrayList<String> typeArray;
ArrayList<String> dairyArray;
ArrayAdapter<String> typeAdapter;
ArrayAdapter<String> flavorAapter;
String typeString, flavourString;
private Object view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.type_of_dairy);
dairyType = (ListView) findViewById(R.id.listView);
dairyFlavour = (ListView) findViewById(R.id.listView2);
typeArray = new ArrayList<String>();
typeAdapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_single_choice, typeArray);
flavorAapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_single_choice, dairyArray);
try
{
ConnectionHelper connectionHelper = new ConnectionHelper();
statement = connectionHelper.getConnection().createStatement();
ResultSet resultSet = statement.executeQuery("select Name from tblProductCategory where TypeId=1");
if(resultSet.next()) {
do {
typeString=resultSet.getString(resultSet.findColumn("Name"));
typeArray.add(typeString);
dairyType.setAdapter(typeAdapter);
}while(resultSet.next());
}
}
catch (SQLException e)
{
}
dairyType.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try{
ConnectionHelper connectionHelper = new ConnectionHelper();
statement2 = connectionHelper.getConnection().createStatement();
ResultSet resultSet = statement2.executeQuery("select username from tblUser");
if(resultSet.next())
{
do {
flavourString = resultSet.getString(resultSet.findColumn("UserName"));
dairyArray.add(flavourString);
dairyFlavour.setAdapter(flavorAapter);
} while (resultSet.next());
}
}catch (SQLException e)
{
Toast.makeText(getApplicationContext(), "Problem detected", Toast.LENGTH_LONG).show();
}
}
});
i want that as i select an item from first ListView(dairyType), some data from another table of my DB be selected and shown in second ListView(dairyFlavour), and this part i said this :
dairyType.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
try{
ConnectionHelper connectionHelper = new ConnectionHelper();
statement2 = connectionHelper.getConnection().createStatement();
ResultSet resultSet = statement2.executeQuery("select username from tblUser");
if(resultSet.next())
{
do {
flavourString = resultSet.getString(resultSet.findColumn("UserName"));
dairyArray.add(flavourString);
dairyFlavour.setAdapter(flavorAapter);
} while (resultSet.next());
}
}catch (SQLException e)
{
Toast.makeText(getApplicationContext(), "Problem detected", Toast.LENGTH_LONG).show();
}
}
});
but i get myAppclication stopped in my android device and javaNullPointExecption in android studio,
However by this connection to DB i have shown the firstListViewand Loged into the App.
From your given code, It seems you forgot to initialise the "dairyArray".
Initialise it first , then add Strings to it.
You might be getting error on "dairyArray.add(flavourString);" , as dairyArray is not initialised.
I hope it will work.
As my Friend #harish said i didnt assign dairyArray in my code, so that related adapter returns nothing,
But i act on the selected item via this code :
public void onClick(View v) {
String str;
str=flavorAapter.getItem(dairyFlavour.getCheckedItemPosition()).toString();
And then return the str.