Got a java.lang.IllegalStateException: The specified child already has a parent - java

I have added two LinearLayouts and on those layouts, I add dynamically Checkboxes. The final purpose is to store data in a database.
I am getting this error:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.freedomkitchen.sonali.freedomkitchen/com.freedomkitchen.sonali.freedomkitchenAndroidApp.AddRecipes}:
java.lang.IllegalStateException: The specified child already has a
parent. You must call removeView() on the child's parent first.
Can you help me to find the problem, please? Thanks.
This is my code:
public class AddRecipes extends AppCompatActivity {
static int a=0,b=0,c=0,d=0;
static int id=0;
public int x;
int idvalueVeg;
int idvalueFruits;
int idvalueGrains;
int idvalueDairy;
int idvalueSeaFood;
int end_of_sup_ing;
int sup_ing_id;
ArrayList<String> Main_Ingredients;
ArrayList<String> Supporting_Ingredients;
LinearLayout ll;
LinearLayout ll2;
Spinner FoodCatValue;
public String MealSelected;
EditText RecipeNameValue;
public Spinner sItems;
private static final boolean AUTO_HIDE = true;
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
private static final int UI_ANIMATION_DELAY = 300;
private final Handler mHideHandler = new Handler();
private View mContentView;
private final Runnable mHidePart2Runnable = new Runnable() {
#SuppressLint("InlinedApi")
#Override
public void run() {
mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
};
private View mControlsView;
private final Runnable mShowPart2Runnable = new Runnable() {
#Override
public void run() {
// Delayed display of UI elements
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.show();
}
mControlsView.setVisibility(View.VISIBLE);
}
};
private boolean mVisible;
private final Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
hide();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addrecipes);
ll = (LinearLayout) findViewById(R.id.chk_layout);
ll2 = (LinearLayout) findViewById(R.id.chk_layout2);
FoodCatValue = (Spinner)findViewById(R.id.spinnerFoodCat);
Resources res = getResources();
String[] Appetizers = res.getStringArray(R.array.Appetizer_Meals);
String[] Main_Course = res.getStringArray(R.array.Main_Course_Meals);
String[] Desserts = res.getStringArray(R.array.Desserts_Meals);
ArrayList<String> AppetizerList = new ArrayList<String>(Arrays.asList(Appetizers));
ArrayList<String> Main_CourseList = new ArrayList<String>(Arrays.asList(Main_Course));
ArrayList<String> DessertList = new ArrayList<String>(Arrays.asList(Desserts));
if(FoodCatValue.getSelectedItem().toString().equals("Appetizers")){
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, AppetizerList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sItems = (Spinner) findViewById(R.id.spinnerMealCat);
sItems.setAdapter(adapter);
getMealSelectedVal();
}
else if(FoodCatValue.getSelectedItem().toString().equals("Main Course"))
{
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, Main_CourseList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sItems = (Spinner) findViewById(R.id.spinnerMealCat);
sItems.setAdapter(adapter);
getMealSelectedVal();
}
else if(FoodCatValue.getSelectedItem().toString().equals("Dessert")){
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, DessertList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sItems = (Spinner) findViewById(R.id.spinnerMealCat);
sItems.setAdapter(adapter);
getMealSelectedVal();
}
RecipeNameValue =(EditText)findViewById(R.id.RecipeName);
DB_Access mydb=new DB_Access(this);
ArrayList<String> Vegetables=mydb.getIngredients(1);
ArrayList<String> Fruits=mydb.getIngredients(2);
ArrayList<String> Dairy=mydb.getIngredients(3);
ArrayList<String> Grains=mydb.getIngredients(4);
ArrayList<String> Seafood=mydb.getIngredients(5);
ArrayList<String> Sup_Ing=mydb.getSupportingIngredients();
final TextView VegTv = new TextView(this);
VegTv.setText("Vegetables");
ll.addView(VegTv);
for (x=0;x<Vegetables.size(); x++,id++) {
final CheckBox checkbox = new CheckBox(this);
checkbox.setId(id);
String Item = Vegetables.get(x);
checkbox.setText(Item);
ll.addView(checkbox);
idvalueVeg=id;
}
TextView FruitsTv = new TextView(this);
FruitsTv.setText("Fruits");
ll.addView(FruitsTv);
for (x=0;x<Fruits.size(); x++,id++) {
CheckBox checkbox = new CheckBox(this);
checkbox.setId(id);
String Item = Fruits.get(x);
checkbox.setText(Item);
ll.addView(checkbox);
idvalueFruits=id;
}
TextView GrainsTv = new TextView(this);
GrainsTv.setText("Grains");
ll.addView(GrainsTv);
for (x=0;x<Grains.size(); x++,id++) {
CheckBox checkbox = new CheckBox(this);
checkbox.setId(id);
String Item = Grains.get(x);
checkbox.setText(Item);
ll.addView(checkbox);
idvalueGrains=id;
}
TextView DairyTv = new TextView(this);
DairyTv.setText("Dairy");
ll.addView(DairyTv);
for(x=0;x<Dairy.size(); x++,id++) {
CheckBox checkbox = new CheckBox(this);
checkbox.setId(id);
String Item = Dairy.get(x);
checkbox.setText(Item);
ll.addView(checkbox);
idvalueDairy=id;
}
TextView SeafoodTv = new TextView(this);
SeafoodTv.setText("Seafood");
ll.addView(DairyTv);
for(x=0;x<Seafood.size(); x++,id++) {
CheckBox checkbox = new CheckBox(this);
checkbox.setId(id);
String Item = Seafood.get(x);
checkbox.setText(Item);
ll2.addView(checkbox);
idvalueSeaFood=id;
}
TextView supIng = (TextView)findViewById(R.id.sup_ingTextView);
DairyTv.setText("Supporting Ingredients");
ll.addView(supIng);
sup_ing_id = idvalueSeaFood;
for(x=0;x<Sup_Ing.size(); x++,id++) {
CheckBox checkbox = new CheckBox(this);
checkbox.setId(id);
String Item = Sup_Ing.get(x);
checkbox.setText(Item);
ll.addView(checkbox);
end_of_sup_ing=id;
}
}
public void getMealSelectedVal(){
MealSelected= sItems.getSelectedItem().toString();
}
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
}
private void hide() {
// Hide UI first
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.hide();
}
mControlsView.setVisibility(View.GONE);
mVisible = false;
// Schedule a runnable to remove the status and navigation bar after a delay
mHideHandler.removeCallbacks(mShowPart2Runnable);
mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
}
#SuppressLint("InlinedApi")
private void show() {
// Show the system bar
mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
mVisible = true;
// Schedule a runnable to display UI elements after a delay
mHideHandler.removeCallbacks(mHidePart2Runnable);
mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
}
public void btnAddRecipes(View v){
GetInfo();
DB_Access mydb=new DB_Access(this);
EditText ins =(EditText)findViewById(R.id.RecipeTextArea);
mydb.adduserRecipes(FoodCatValue.getSelectedItem().toString(),MealSelected,RecipeNameValue.getText().toString(), Main_Ingredients,Supporting_Ingredients,ins.getText().toString());
}
public void GetInfo(){
Main_Ingredients=new ArrayList<String>(200);
Supporting_Ingredients=new ArrayList<String>(200);
for(x=0;x<id;x++){
CheckBox cb=(CheckBox)findViewById(x);
if(cb.isChecked()){
{
String item=cb.getText().toString();
Main_Ingredients.add(item);
}
}
}
//disp main ing
for(int i=0;i<Main_Ingredients.size();i++){
Log.i("Main_Ing:",Main_Ingredients.get(i));
}
for(x=sup_ing_id;x<=end_of_sup_ing;x++){
CheckBox cb=(CheckBox)findViewById(x);
if(cb.isChecked()){
{
String item=cb.getText().toString();
Supporting_Ingredients.add(item);
}
}
}
for(int i=0;i<Supporting_Ingredients.size();i++){
Log.i("Sup_Ing:",Supporting_Ingredients.get(i));
}
}
}
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:background="#cdd2ea"
android:id="#+id/RL"
android:orientation="vertical"
android:weightSum="1">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/sv"
android:fillViewport="true"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/buttonAddRecipes">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/l_layout"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Add a New Recipe"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Food Category :"
android:id="#+id/textView11"
android:layout_marginTop="25dp"
android:layout_below="#+id/textView"
android:layout_alignParentStart="true"
android:layout_marginStart="47dp" />
<Spinner
android:layout_width="244dp"
android:layout_height="match_parent"
android:id="#+id/spinnerFoodCat"
android:entries="#array/Food_Cat"
android:layout_gravity="center" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Meal Category :"
android:id="#+id/textView12"
android:layout_marginTop="25dp"
android:layout_below="#+id/textView"
android:layout_alignParentStart="true"
android:layout_marginStart="47dp" />
<Spinner
android:layout_width="244dp"
android:layout_height="match_parent"
android:id="#+id/spinnerMealCat"
android:layout_gravity="center" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Recipe Name :"
android:id="#+id/textView13"
android:layout_marginTop="25dp"
android:layout_below="#+id/spinner"
android:layout_alignParentStart="true"
android:layout_marginStart="47dp" />
<EditText
android:layout_width="271dp"
android:layout_height="match_parent"
android:id="#+id/RecipeName"
android:hint="Enter Recipe Name"
android:layout_below="#+id/textView13"
android:layout_gravity="center_horizontal" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Main Ingredients:"
android:id="#+id/textView15"
android:layout_marginStart="47dp" />
<LinearLayout
android:orientation="vertical"
android:id="#+id/chk_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="#+id/sup_ingTextView"
android:layout_marginStart="47dp" />
<LinearLayout
android:orientation="vertical"
android:id="#+id/chk_layout2"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
<TextView
android:layout_width="303dp"
android:layout_height="match_parent"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Instructions :"
android:id="#+id/textView17"
android:layout_marginTop="25dp"
android:layout_below="#+id/textView15"
android:layout_alignParentStart="true"
android:layout_marginStart="25dp"
android:layout_marginRight="20dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:inputType="textMultiLine"
android:ems="10"
android:id="#+id/RecipeTextArea"
android:editable="true"
android:layout_marginTop="25dp"
android:enabled="true"
android:minLines="6"
android:maxLines="6"
android:isScrollContainer="true"
android:hint="Enter Recipe Instructions here."
android:background="#fafafa"
android:textIsSelectable="true"
android:focusable="true"
android:gravity="top"
android:padding="24dp"
style="#style/Base.TextAppearance.AppCompat.Large"
/>
</LinearLayout>
</ScrollView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add Recipe"
android:id="#+id/buttonAddRecipes"
android:capitalize="words"
android:clickable="true"
android:longClickable="false"
android:background="#4052b5"
android:textColor="#fefefe"
android:textSize="#dimen/abc_select_dialog_padding_start_material"
android:onClick="btnAddRecipes"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>

This exception is fired then you try to add some view twice to layout.
You copypasted your code and didn't change it here
TextView SeafoodTv = new TextView(this);
SeafoodTv.setText("Seafood");
ll.addView(DairyTv);
I beleive it should be
TextView SeafoodTv = new TextView(this);
SeafoodTv.setText("Seafood");
ll.addView(SeafoodTv);
To avoid such mistakes it's better to put static views in xml layout.

Related

how may i resolve ListView Problem ? ERROR: on a null object reference

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

Activity is overlapping fragment home

I'm developing a Calorie app where the user can delete an item from the listview.
PROBLEM: When the user clicks on the item it goes to the calorie details activity,when they click delete it goes back to the home fragment. As soon as I click on add another entry it crashes. Also when it goes back to fragment home it doesnt look the same the calorie details activity is over lapping the fragment home not completely replacing it.
calorieDetails.java
public class CalorieDetails extends AppCompatActivity {
private TextView foodName, calories, dateTaken;
private Button shareButton;
private int foodId;
private Button deleteButton;
private android.support.v4.app.FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calorie_details);
foodName = (TextView) findViewById(R.id.detsFoodName);
calories = (TextView) findViewById(R.id.detscaloriesValue);
dateTaken = (TextView) findViewById(R.id.detsDateText);
deleteButton = (Button) findViewById(R.id.deleteButton);
Food food = (Food) getIntent().getSerializableExtra("userObj");
foodName.setText(food.getFoodName());
calories.setText(String.valueOf(food.getCalories()));
dateTaken.setText(food.getRecordDate());
foodId = food.getFoodId();
foodName.setTextColor(Color.WHITE);
dateTaken.setTextColor(Color.WHITE);
calories.setTextSize(34.9 f);
calories.setTextColor(Color.WHITE);
deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//TODO: put delete functionality here
android.support.v7.app.AlertDialog.Builder alert = new
android.support.v7.app.AlertDialog.Builder(CalorieDetails.this);
alert.setTitle("Delete?");
alert.setMessage("Are you sure you want to delete this item?");
alert.setNegativeButton("No", null);
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
DatabaseHandler dba = new
DatabaseHandler(getApplicationContext());
dba.deleteFood(foodId);
Toast.makeText(CalorieDetails.this, "Food Item
Deleted!", Toast.LENGTH_SHORT).show();
FragmentHome homeFragment = new FragmentHome();
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.FragmentHolder,
homeFragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit();
}
});
alert.show();
}
});
}
}
FragmentHome.java
public class FragmentHome extends Fragment implements
View.OnClickListener {
private TextView caloriesTotal;
private TextView caloriesRemain;
private ListView listView;
private LinearLayout mLayout;
ImageButton AddEntrybtn;
ImageButton ResetEntry;
Context context;
int goalCalories;
int totalCalorie;
Button mButton;
//Database
private DatabaseHandler dba;
private ArrayList < Food > dbFoods = new ArrayList < > ();
private CustomListViewAdapter foodAdapter;
private Food myFood;
//fragment
private android.support.v4.app.FragmentManager fragmentManager;
private FragmentTransaction fragmentTransaction;
public FragmentHome() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myView = inflater.inflate(R.layout.fragment_home, container,
false);
caloriesTotal = (TextView)
myView.findViewById(R.id.tv_calorie_amount);
caloriesRemain = (TextView) myView.findViewById(R.id.calorieRemain);
listView = (ListView) myView.findViewById(R.id.ListId);
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getActivity());
PreferenceManager.setDefaultValues(getActivity(),
R.xml.activity_preference, false);
goalCalories =
Integer.parseInt(prefs.getString("prefs_key_daily_calorie_amount",
"2000"));
AddEntrybtn = (ImageButton) myView.findViewById(R.id.AddItems);
AddEntrybtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
((appMain) getActivity()).loadSelection(4);
}
});
ResetEntry = (ImageButton) myView.findViewById(R.id.ResetEntry);
ResetEntry.setOnClickListener(this);
refreshData();
return myView;
}
public void reset() {
dbFoods.clear();
dba = new DatabaseHandler(getActivity());
ArrayList < Food > foodsFromDB = dba.getFoods();
//Loop
for (int i = 0; i < foodsFromDB.size(); i++) {
String name = foodsFromDB.get(i).getFoodName();
String date = foodsFromDB.get(i).getRecordDate();
int cal = foodsFromDB.get(i).getCalories();
int foodId = foodsFromDB.get(i).getFoodId();
Log.v("Food Id", String.valueOf(foodId));
myFood = new Food();
myFood.setFoodId(foodId);
myFood.setFoodName(name);
myFood.setCalories(cal);
myFood.setRecordDate(date);
dbFoods.clear();
dbFoods.remove(myFood);
foodsFromDB.remove(myFood);
dba.deleteFood(foodId);
}
dba.close();
//setting food Adapter:
foodAdapter = new CustomListViewAdapter(getActivity(),
R.layout.row_item, dbFoods);
listView.setAdapter(foodAdapter);
foodAdapter.notifyDataSetChanged();
}
public void refreshData() {
dbFoods.clear();
dba = new DatabaseHandler(getActivity());
ArrayList < Food > foodsFromDB = dba.getFoods();
totalCalorie = dba.totalCalories();
String formattedCalories = Utils.formatNumber(totalCalorie);
String formattedRemain = Utils.formatNumber(goalCalories -
totalCalorie);
//setting the editTexts:
caloriesTotal.setText("Total Calories: " + formattedCalories);
caloriesRemain.setText(formattedRemain);
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(getContext());
PreferenceManager.setDefaultValues(getActivity(),
R.xml.activity_preference, false);
goalCalories =
Integer.parseInt(prefs.getString("prefs_key_daily_calorie_amount", "2000"));
//Loop
for (int i = 0; i < foodsFromDB.size(); i++) {
String name = foodsFromDB.get(i).getFoodName();
String date = foodsFromDB.get(i).getRecordDate();
int cal = foodsFromDB.get(i).getCalories();
int foodId = foodsFromDB.get(i).getFoodId();
Log.v("Food Id", String.valueOf(foodId));
myFood = new Food();
myFood.setFoodId(foodId);
myFood.setFoodName(name);
myFood.setCalories(cal);
myFood.setRecordDate(date);
dbFoods.add(myFood);
}
dba.close();
//setting food Adapter:
foodAdapter = new CustomListViewAdapter(getActivity(),
R.layout.row_item, dbFoods);
listView.setAdapter(foodAdapter);
foodAdapter.notifyDataSetChanged();
}
//save prefs
public void savePrefs(String key, int value) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.apply();
}
//get prefs
public int loadPrefs(String key, int value) {
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(getContext());
return sharedPreferences.getInt(key, value);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle username = getActivity().getIntent().getExtras();
String username1 = username.getString("Username");
TextView userMain = (TextView) getView().findViewById(R.id.User);
userMain.setText(username1);
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
startActivity(new Intent(getContext(), MainActivity.class));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.AddItems:
AddEntry addEntry = new AddEntry();
fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(R.id.FragmentHolder, addEntry).commit();
break;
case R.id.action_settings:
Intent preferenceScreenIntent = new Intent(getContext(),
PreferenceScreenActivity.class);
startActivity(preferenceScreenIntent);
break;
case R.id.ResetEntry:
reset();
break;
}
}
activity_calorie_details.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:id="#+id/FragmentHolder"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
tools:context=".CalorieDetails"
android:background="#drawable/imgbackground2"
style="#style/AppTheme">
<ImageView
android:id="#+id/logo"
android:src="#drawable/weight"
android:layout_centerHorizontal="true"
android:layout_width="180dp"
android:layout_height="180dp" />
<LinearLayout
android:id="#+id/layout"
android:elevation="4dp"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/logo"
android:layout_centerHorizontal="true">
<TextView
android:id="#+id/detsFoodName"
android:elevation="4dp"
android:text="dkdad"
android:textSize="19sp"
android:textStyle="bold"
android:layout_marginTop="18dp"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/detsCaloriesTitle"
android:text="Calories:"
android:textSize="18sp"
android:layout_marginTop="18dp"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/detscaloriesValue"
android:text="200"
android:textSize="18sp"
android:layout_marginTop="18dp"
android:layout_gravity="center_horizontal"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/detsDateText"
android:text="Consumed on..."
android:textStyle="italic"
android:textSize="14sp"
android:layout_marginTop="14dp"
android:layout_gravity="center_horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="#+id/deleteButton"
android:text="DELETE"
android:textColor="#ffff"
android:textStyle="bold"
android:layout_marginTop="20dp"
android:layout_gravity="center_horizontal"
android:layout_width="200dp"
android:background="#color/colorBackground2"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
Home_fragment.xml
<FrameLayout
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:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:background="#drawable/imgbackground2"
style="#style/AppTheme"
tools:context="layout.HomeFragment"
android:id="#+id/HomeFragment">
<RelativeLayout
android:layout_width="match_parent"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
android:layout_height="271dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Welcome,"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="85dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/emptyString"
android:id="#+id/User"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/tv_main_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="24dp"
android:textSize="24sp"
android:textColor="#ffffff"
android:text="#string/activity_text_calorie_title"
android:layout_gravity="center_horizontal"
android:textAlignment="center"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/tv_calorie_amount"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:paddingTop="0dp"
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#ffffff"
tools:text="1600"
android:paddingRight="0dp"
android:paddingLeft="10dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="40dp"
android:layout_below="#+id/tv_main_title"
android:layout_alignParentStart="true"
android:gravity="center"
android:layout_alignParentBottom="false"
android:layout_alignParentLeft="false"
android:layout_alignParentRight="false" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/AddItems"
android:background="?android:attr/selectableItemBackground"
android:src="#drawable/add"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_gravity="right"
android:layout_below="#+id/tv_calorie_amount"
android:layout_alignParentEnd="true" />
<TextView
tools:text="1600"
android:id="#+id/calorieRemain"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:paddingTop="0dp"
android:textSize="20dp"
android:textStyle="bold"
android:textColor="#ffffff"
android:paddingRight="0dp"
android:paddingLeft="10dp"
android:layout_gravity="center_horizontal"
android:gravity="center"
android:layout_below="#+id/tv_main_title"
android:layout_toEndOf="#+id/textView" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ResetEntry"
android:background="?android:attr/selectableItemBackground"
android:src="#drawable/removecircle"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_gravity="right"
android:paddingRight="0dp"
android:layout_alignBottom="#+id/AddItems"
android:layout_toStartOf="#+id/AddItems" />
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="274dp"
android:layout_gravity="center_horizontal|bottom">
<ListView
android:id="#+id/ListId"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:dividerHeight="2dp"
android:divider="#212121"
android:scrollingCache="false"
android:smoothScrollbar="false"
android:layout_below="#+id/tv_calorie_amount"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"></ListView>
</LinearLayout>
</FrameLayout>
Here is a screenshot of what happens after clicking delete:
http://www.tiikoni.com/tis/view/?id=c0939b3
Here is what the Home Fragment Looks like before deleting item:
http://www.tiikoni.com/tis/view/?id=70e433d
logcat when I click Delete on the Calorie Details fragment
05-04 02:25:25.561 5830-5830/com.example.treycoco.calorietracker
E/MotionRecognitionManager: mSContextService =
android.hardware.scontext.ISContextService$Stub$Proxy#14b764b
05-04 02:25:25.571 5830-5830/com.example.treycoco.calorietracker
E/MotionRecognitionManager: motionService =
com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy#42e6828
05-04 02:25:25.571 5830-5830/com.example.treycoco.calorietracker
E/MotionRecognitionManager: motionService =
com.samsung.android.motion.IMotionRecognitionService$Stub$Proxy#42e6828
05-04 02:25:25.581 5830-5830/com.example.treycoco.calorietracker
E/ViewRootImpl: sendUserActionEvent() mView == null
When I click on Add Entry After Clicking on Delete
Logcat:
05-04 02:28:04.761 5830-
5830/com.example.treycoco.calorietracker E/AndroidRuntime:
FATAL EXCEPTION: main
Process: com.example.treycoco.calorietracker, PID: 5830
java.lang.ClassCastException
com.example.treycoco.calorietracker.CalorieDetails cannot be cast
to com.example.treycoco.calorietracker.appMain
at com.example.treycoco.calorietracker.
FragmentHome$1.onClick(FragmentHome.java:118)
at android.view.View.performClick(View.java:5697)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run
(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

implementation of listViews and images

My problem is, i want to implement a activity with a list and image and in the bottom of image there is four text .When I am going to open my app it has to show one selected text with its related image and list as default.when clicking on rest of the text it has to show their related list and images in the same activity respectively.Since i am new to android please help me out.
Here is xml code
<RelativeLayout
android:id="#+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="2.5"
>
<ImageView
android:id="#+id/mainimage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/pestf"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="20dp"
android:orientation="horizontal"
android:layout_gravity="bottom"
android:layout_alignParentBottom="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pest Control"
android:id="#+id/pestf"
android:onClick="click1"
android:clickable="true"
android:textStyle="normal"
android:textSize="15dp"
android:textColor="#cf0c07"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/packf"
android:layout_marginLeft="5dp"
android:id="#+id/packf"
android:onClick="click1"
android:clickable="true"
android:textStyle="normal"
android:textSize="15dp"
android:textColor="#cf0c07"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cleaning"
android:layout_marginLeft="5dp"
android:id="#+id/cleanf"
android:onClick="click1"
android:clickable="true"
android:textStyle="normal"
android:textSize="15dp"
android:textColor="#cf0c07"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="Landscaping"
android:id="#+id/landf"
android:onClick="click1"
android:clickable="true"
android:layout_marginLeft="5dp"
android:textStyle="normal"
android:textSize="15dp"
android:textColor="#cf0c07"/>
</LinearLayout>
</RelativeLayout>
<ListView
android:id="#+id/lst"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/ll_pest"
android:layout_weight="2.2"
android:background="#FFFFFF"
>
</ListView>
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/lst"
android:layout_weight="3.5"
android:gravity="center"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="5dp"
android:layout_marginTop="3dp"
android:layout_alignParentBottom="true"
android:background="#drawable/border_layout">
<TextView
android:id="#+id/txt_pest_Email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:background="#FFFFFF"
android:text="#string/btn7"
android:drawablePadding="5dp"
android:drawableTop="#drawable/icon7"
android:textStyle="bold"
android:textColor="#000000"
/>
<View
android:layout_width="1dp"
android:layout_height="fill_parent"
android:background="#82020202" />
<TextView
android:id="#+id/txt_pest_phone"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:background="#ffffff"
android:text="#string/btn8"
android:drawablePadding="5dp"
android:drawableTop="#drawable/icon8"
android:textStyle="bold"
android:textColor="#000000"
/>
</LinearLayout>
Here is Activity code
public class demo2 extends AppCompatActivity {
TextView tv1,tv2,tv3,tv4,txtEmail,txtPhone;
ListView lv;
ImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo2);
String[] adobe_products = getResources().getStringArray(R.array.adobe_products);
lv = (ListView) findViewById(R.id.lst);
img = (ImageView) findViewById(R.id.mainimage);
txtEmail=(TextView)findViewById(R.id.txt_pest_Email);
txtPhone=(TextView)findViewById(R.id.txt_pest_phone);
tv1 = (TextView) findViewById(R.id.text1);
tv2 = (TextView) findViewById(R.id.text2);
tv3 = (TextView) findViewById(R.id.text3);
tv4 = (TextView) findViewById(R.id.text4);
lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, adobe_products));
tv1.setTextColor(getResources().getColor(R.color.blue));
txtPhone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mobileNo = "08042589999";
String uri = "tel:" + mobileNo.trim();
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uri));
startActivity(intent);
}
});
txtEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(demo2.this, Booknow.class);
// sending data to new activity
i.putExtra("flag",true);
i.putExtra("cat",1);
startActivity(i);
}
});
// Inflate the layout for this fragment
}
public void click2(View v){
img.setBackgroundResource(R.drawable.packers);
String[] countries = getResources().getStringArray(R.array.country);
lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item1, countries));
tv2.setTextColor(getResources().getColor(R.color.blue));
tv1.setTextColor(getResources().getColor(R.color.red));
tv3.setTextColor(getResources().getColor(R.color.red));
tv4.setTextColor(getResources().getColor(R.color.red));
}
public void click1(View v){
img.setBackgroundResource(R.drawable.pestf);
String[] adobe = getResources().getStringArray(R.array.adobe_products);
lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item1, adobe));
tv1.setTextColor(getResources().getColor(R.color.blue));
tv2.setTextColor(getResources().getColor(R.color.red));
tv3.setTextColor(getResources().getColor(R.color.red));
tv4.setTextColor(getResources().getColor(R.color.red));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Launching new Activity on selecting single List Item
Intent i = new Intent(demo2.this, BedbugControl.class);
// sending data to new activity
i.putExtra("position", position);
startActivity(i);
}
});
}
public void click3(View v){
img.setBackgroundResource(R.drawable.cleaningf);
String[] sweets = getResources().getStringArray(R.array.sweets);
lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item1, sweets));
tv3.setTextColor(getResources().getColor(R.color.blue));
tv1.setTextColor(getResources().getColor(R.color.red));
tv2.setTextColor(getResources().getColor(R.color.red));
tv4.setTextColor(getResources().getColor(R.color.red));
}
public void click4(View v) {
img.setBackgroundResource(R.drawable.landf);
String[] companies = getResources().getStringArray(R.array.company);
lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item1, companies));
tv4.setTextColor(getResources().getColor(R.color.blue));
tv1.setTextColor(getResources().getColor(R.color.red));
tv2.setTextColor(getResources().getColor(R.color.red));
tv3.setTextColor(getResources().getColor(R.color.red));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_demo2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

BaseAdapter gets me only the first position in ListView Android

I've a major isse with an adapter to show every single row item in a ListView and I only get the first value of the index position.
I've an array of comments from a webservice in android. It's an array inside an array.
The main JSONArray it's "noticias" with has a lot of the previews jsonobject. Now: "comments" it's another array.
This is my ContenidoNews.java class. I pass the "comment" array in a intent from the previews Activity:
public class ContenidoNews extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener{
private ActionBar bar;
String tituloDetail;
String fullDetail;
String imagenDetail;
String permalink;
String author;
String authorimg;
String dayofmonth;
String month;
String views;
String totalcomments;
String arraycomments;
private SquareImageView mainPic;
private CircularImageView authorpic;
private TextView authors;
private TextView contentTxt;
private ScrollView scollMain;
private TextView mainTxt;
private Animation animSlideDown;
private RelativeLayout relativeAnim;
private RelativeLayout namereceipt;
private Typeface texto;
private Button btnshare;
// Universal Image Loader
private DisplayImageOptions options;
private ImageLoader il = ImageLoader.getInstance();
private DisplayImageOptions opts;
private File cacheDir;
private String imgauthor;
private TextView tvday;
private TextView tvmonth;
private Typeface textofat;
private LinearLayout datestv;
private WebView webview;
private ArrayList links;
private String urlscap;
private String newstring;
private String copyfull;
private String youtube;
private YouTubePlayerView youTubePlayerView;
private String youtubeb;
private String youtubec;
private String youtubed;
private TextView tvtotal;
private TextView tvvisitas;
private String youtubee;
private String youtubef;
private JSONArray arrayComment;
ArrayList<HashMap<String, String>> arrayofcomments;
private ListView listcomment;
private ListAdapter adapter;
private TextView numbcomment;
private TextView tvcomment;
static String AUTHOR = "comauthor";
static String COMMENT = "comtext";
// Grab URLs from text
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contenido);
bar = getActionBar();
bar.setBackgroundDrawable(getResources().getDrawable(R.drawable.gradiente));
bar.setDisplayHomeAsUpEnabled(true);
bar.setTitle("");
webview = (WebView) findViewById(R.id.wvhit);
webview.getSettings().setJavaScriptEnabled(true);
youTubePlayerView = (YouTubePlayerView)findViewById(R.id.youtubeplayerview);
youTubePlayerView.initialize(API_KEY, this);
Intent i = getIntent();
// Get the result of titulo
tituloDetail = i.getStringExtra("titulo").replace("“", "\"").replace("”", "\"").replace("…", "...").replace("–", "-");
// Get the result of full
fullDetail = i.getStringExtra("full");
// Get the result of imagen
imagenDetail = i.getStringExtra("imagen");
// Get the result of permalink
permalink = i.getStringExtra("permalink");
// Get the result of author
author = i.getStringExtra("author");
// Get the result of authorimg
authorimg = i.getStringExtra("authorimg");
int urlimg = authorimg.lastIndexOf("s=128&");
imgauthor = "http://" + authorimg.substring(9, urlimg + 5);
// Get the result of dayofmonth
dayofmonth = i.getStringExtra("dayofmonth");
// Get the result of month
month = i.getStringExtra("month");
// Get the result of views
views = i.getStringExtra("views");
// Get the result of total comments
totalcomments = i.getStringExtra("totalcomments");
// Get the result of array comments
arraycomments = i.getStringExtra("arraycomments");
webview.setWebViewClient(new WebViewClient());
webview.loadUrl(permalink);
pullLinks(fullDetail);
copyfull = fullDetail;
new JSONParser().execute();
texto = Typeface.createFromAsset(this.getAssets(),
"Light.ttf");
textofat = Typeface.createFromAsset(this.getAssets(),
"Bold.ttf");
listcomment = (ListView) findViewById(R.id.listofcomments);
datestv = (LinearLayout) findViewById(R.id.datestv);
tvday = (TextView) findViewById(R.id.tvday);
tvmonth = (TextView) findViewById(R.id.tvmonth);
tvday.setText(dayofmonth);
tvmonth.setText(month);
tvtotal = (TextView) findViewById(R.id.totalvisitas);
tvtotal.setText(views);
tvtotal.setTypeface(textofat);
tvvisitas = (TextView) findViewById(R.id.TVvisitas);
if(views.contentEquals("1")){
tvvisitas.setText("VISITA");
}else{
tvvisitas.setText("VISITAS");
}
tvvisitas.setTypeface(texto);
tvday.setTypeface(textofat);
tvmonth.setTypeface(texto);
mainPic = (SquareImageView) findViewById(R.id.fullimg);
authorpic = (CircularImageView) findViewById(R.id.profile_settings_img);
btnshare = (Button) findViewById(R.id.btnshare);
ScrollView scrollView = (ScrollView) findViewById(R.id.scroll_view);
if (scrollView instanceof Parallaxor) {
((Parallaxor) scrollView).parallaxViewBy(mainPic, 0.6f);
}
relativeAnim = (RelativeLayout) findViewById(R.id.animtext);
animSlideDown = AnimationUtils.loadAnimation(getApplicationContext(),
R.animator.slidetodown);
relativeAnim.startAnimation(animSlideDown);
il.displayImage(imagenDetail, mainPic,opts,new ImageLoadingListener() {
#Override
public void onLoadingStarted(String s, View itemView) {
}
#Override
public void onLoadingFailed(String s, View itemView, FailReason failReason) {
}
#Override
public void onLoadingComplete(String imageUri, View itemView, Bitmap bitmap) {
SquareImageView imageView = (SquareImageView) itemView;
if (bitmap != null) {
FadeInBitmapDisplayer.animate(imageView, 500);
}
}
#Override
public void onLoadingCancelled(String s, View view) {
}
});
il.displayImage(imgauthor, authorpic,opts,new ImageLoadingListener() {
#Override
public void onLoadingStarted(String s, View itemView) {
}
#Override
public void onLoadingFailed(String s, View itemView, FailReason failReason) {
}
#Override
public void onLoadingComplete(String imageUri, View itemView, Bitmap bitmap) {
CircularImageView imageView = (CircularImageView) itemView;
if (bitmap != null) {
FadeInBitmapDisplayer.animate(imageView, 500);
}
}
#Override
public void onLoadingCancelled(String s, View view) {
}
});
contentTxt = (TextView) findViewById(R.id.textnoti);
if(links.size() != 0 && urlscap.contains("youtu")){
youTubePlayerView.setVisibility(View.VISIBLE);
contentTxt.setText(newstring);
}else{
youTubePlayerView.setVisibility(View.GONE);
contentTxt.setText(fullDetail);
}
authors = (TextView) findViewById(R.id.authors);
authors.setText(author);
authors.setTypeface(texto);
mainTxt = (TextView) findViewById(R.id.tituloreceipt);
mainTxt.setText(tituloDetail);
mainTxt.setTypeface(texto);
namereceipt = (RelativeLayout) findViewById(R.id.namereceipt);
Resources res = getResources();
final TypedArray myImages = res.obtainTypedArray(R.array.image);
final Random random = new Random();
//Genrate a random index in the range
int randomInt = random.nextInt(myImages.length());
// Generate the drawableID from the randomInt
int drawableID = myImages.getResourceId(randomInt, -1);
namereceipt.setBackgroundResource(drawableID);
numbcomment = (TextView) findViewById(R.id.numbofcomments);
numbcomment.setText(totalcomments);
tvcomment = (TextView) findViewById(R.id.textforcomments);
if(totalcomments.contentEquals("1")){
tvcomment.setText("COMENTARIO");
}else{
tvcomment.setText("COMENTARIOS");
}
}
My AsyncTask
private class JSONParser extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
arrayofcomments = new ArrayList<HashMap<String, String>>();
arrayComment = new JSONArray(arraycomments);
for(int e = 0; e < arrayComment.length(); e++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject come = arrayComment.getJSONObject(e);
map.put("comauthor", come.getString("comment_author"));
map.put("comtext", come.getString("comment_content"));
arrayofcomments.add(map);
}
} catch (Exception e1) {
}
return null;
}
#Override
protected void onPostExecute(Void args) {
adapter = new ListAdapter(getApplicationContext(), arrayofcomments);
listcomment.setAdapter(adapter);
}
}
The result of arrayComment it's:
[
{
"comment_author_url": "http://www.xxxx.com",
"comment_type": "",
"comment_author_IP": "xxxx",
"comment_author": "Mariano xxxx",
"comment_parent": "0",
"comment_agent": "xxxx",
"comment_karma": "0",
"comment_author_email": "xxxx#xxxx.com",
"comment_date": "2014-10-08 17:31:58",
"comment_post_ID": "593",
"comment_ID": "8",
"comment_content": "Prueba",
"user_id": "2",
"comment_date_gmt": "2014-10-08 20:31:58",
"comment_approved": "1"
},
{
"comment_author_url": "",
"comment_type": "",
"comment_author_IP": "xxxx",
"comment_author": "Susana A xxxx",
"comment_parent": "0",
"comment_agent": "xxxx",
"comment_karma": "0",
"comment_author_email": "xxxxxx#yahoo.com.ar",
"comment_date": "2014-10-08 08:28:00",
"comment_post_ID": "593",
"comment_ID": "7",
"comment_content": "una clarísima definición",
"user_id": "0",
"comment_date_gmt": "2014-10-08 11:28:00",
"comment_approved": "1"
}
]
So far so good... now I need to pass all this to my adapter:
public class ListAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
private ArrayList<HashMap<String, String>> data;
private HashMap<String, String> resultp;
public ListAdapter(Context context,
ArrayList<HashMap<String, String>> d) {
this.context = context;
data = d;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView author;
TextView comment;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.comment_item, parent, false);
resultp = new HashMap<String, String>();
final int pos = position;
resultp = data.get(position);
Log.e("data", data.get(position).toString());
author = (TextView) itemView.findViewById(R.id.tvauthorcomment);
author.setText(resultp.get(ContenidoNews.AUTHOR));
author.setTypeface(textofat);
comment = (TextView) itemView.findViewById(R.id.tvofcomment);
comment.setText(resultp.get(ContenidoNews.COMMENT));
comment.setTypeface(texto);
return itemView;
}
}
The result of Log.e("data full", data.toString()); its:
10-08 22:33:40.564: E/data full(26463): [{comtext=Prueba, comauthor=Mariano xxxx}, {comtext=una clarísima definición, comauthor=Susana A xxxx}]
Which, by the way, prints 7 times in the log... but it has the 2 values as I need.
Now... this it's what Log.e("data", data.get(position).toString()); gives me:
10-08 22:21:11.444: E/data(24618): {comtext=Prueba, comauthor=Mariano xxxx}
And:
author.setText(resultp.get(ContenidoNews.AUTHOR));
comment.setText(resultp.get(ContenidoNews.COMMENT));
In the adapter also only gave me the first value in my listview (comment_item.xml):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/tvauthorcomment"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:paddingLeft="20dp"
android:text="Autor Comentario"
android:textColor="#707070"
android:textSize="20sp" />
<TextView
android:id="#+id/tvofcomment"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_marginTop="5dp"
android:paddingLeft="30dp"
android:paddingRight="20dp"
android:text="Contenido del comentario"
android:textColor="#707070"
android:textSize="19sp" />
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#BBBBBB" />
</LinearLayout>
</LinearLayout>
I can only get the first value... I can't fix this. I'm stock since a lot of hours and nothing. I don't understand what it's the problem. Please, help!
I would thanks any answer in advance!
EDIT: This is my contenido.xml with the scrollview and the listview
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res/com.renderas.suup"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical" xmlns:app1="http://schemas.android.com/apk/res/com.mkiisoft.masradio">
<WebView
android:id="#+id/wvhit"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone" />
<com.mkiisoft.masradio.utils.SquareImageView
android:id="#+id/fullimg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:scaleType="centerCrop" />
<LinearLayout
android:id="#+id/datestv"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="190dp"
android:background="#90000000" >
<TextView
android:id="#+id/tvday"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:paddingLeft="10dp"
android:text="04"
android:textColor="#FFF"
android:textSize="24sp" />
<TextView
android:id="#+id/tvmonth"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:gravity="center"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="Octubre"
android:textColor="#FFF"
android:textSize="24sp" />
</LinearLayout>
<uk.co.chrisjenx.paralloid.views.ParallaxScrollView
android:id="#+id/scroll_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:scrollbars="none" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingTop="240dp" >
<FrameLayout
android:id="#+id/imagecontainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RelativeLayout
android:id="#+id/namereceipt"
android:layout_width="fill_parent"
android:layout_height="80dp"
android:layout_gravity="bottom"
android:background="#drawable/bggreenyl" >
<TextView
android:id="#+id/tituloreceipt"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="top|left"
android:paddingBottom="8dp"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:paddingTop="8dp"
android:text="Noticia Titulo"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFF"
android:textSize="24sp" />
</RelativeLayout>
</FrameLayout>
<RelativeLayout
android:id="#+id/animtext"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/imagecontainer"
android:background="#FFFFFF" >
<com.mkiisoft.masradio.utils.CircularImageView
android:id="#+id/profile_settings_img"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:src="#drawable/emptypro" />
<TextView
android:id="#+id/authors"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_toRightOf="#id/profile_settings_img"
android:gravity="center_vertical"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#606060"
android:textSize="21sp" />
<LinearLayout
android:id="#+id/linearviews"
android:layout_width="wrap_content"
android:layout_height="22dp"
android:layout_below="#id/authors"
android:layout_marginLeft="15dp"
android:layout_marginTop="8dp"
android:orientation="horizontal" >
<ImageView
android:id="#+id/imgvisitas"
android:layout_width="20dp"
android:layout_height="20dp"
android:layout_gravity="center"
android:layout_marginTop="2dp"
android:alpha="0.7"
android:src="#drawable/eyeviewsblack" />
<TextView
android:id="#+id/totalvisitas"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:gravity="center_vertical"
android:paddingLeft="10dp"
android:text="7"
android:textColor="#606060"
android:textSize="17sp" />
<TextView
android:id="#+id/TVvisitas"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:gravity="center_vertical"
android:paddingLeft="5dp"
android:text="VISITAS"
android:textColor="#606060"
android:textSize="17sp" />
</LinearLayout>
<Button
android:id="#+id/btnshare"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_below="#id/linearviews"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="12dp"
android:background="#drawable/share_btn"
android:text="COMPARTIR"
android:textColor="#color/checktxt" />
<TextView
android:id="#+id/textnoti"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/btnshare"
android:paddingBottom="20dp"
android:paddingLeft="12dp"
android:paddingRight="12dp"
android:paddingTop="10dp"
android:text="Texto de la noticia"
android:textColor="#707070"
android:textSize="18sp" />
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtubeplayerview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/textnoti"
android:layout_marginBottom="20dp"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
android:layout_marginTop="5dp" />
<LinearLayout
android:id="#+id/linearofcomments"
android:layout_width="fill_parent"
android:layout_height="30dp"
android:layout_below="#id/youtubeplayerview"
android:layout_marginLeft="15dp"
android:gravity="center_vertical|left" >
<TextView
android:id="#+id/numbofcomments"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:text="0"
android:textColor="#707070"
android:textSize="23sp" />
<TextView
android:id="#+id/textforcomments"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginLeft="5dp"
android:text="COMENTARIOS"
android:textColor="#707070"
android:textSize="23sp" />
</LinearLayout>
<ListView
android:id="#+id/listofcomments"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_below="#id/linearofcomments"
android:layout_marginBottom="30dp"
android:layout_marginTop="5dp" >
</ListView>
</RelativeLayout>
</RelativeLayout>
</uk.co.chrisjenx.paralloid.views.ParallaxScrollView>
</RelativeLayout>
We shouldn’t use ListView inside the ScrollView because the list view is already ScrollView, the items in list view are already scrollable..
If you use then the list view will show only one item from the adapter.
Check this post ListView inside scrollview for more details...

Android add row to table on button click

I have a TableLayout in my application. I have Two definite Rows so far. One Row has static items assigned to it, and the other has 3 spinners assigned top it.
What I'd like to do is, add a new TableRow when ever I click on a button. So far I have the following code:
<TableRow
android:layout_width="fill_parent">
android:stretchColumns="0,1,2"
<Spinner
android:padding="3dip"
android:gravity="left"
android:id="#+id/Spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp" />
<Spinner
android:padding="3dip"
android:gravity="left"
android:id="#+id/Spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp" />
<Spinner
android:padding="3dip"
android:gravity="left"
android:id="#+id/spinner3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp" />
</TableRow>
This is just me second row, the row that I want to add when ever I click said button. MY question is, how do I add the following row into my view, every time the user clicks the button? The values of the spinners will differ, but the variables will stay the same.
Edit:
More code:
/* Find Tablelayout defined in teh XML file */
TableLayout tl = (TableLayout) findViewById(R.id.listTable);
/* Create a new row to be added. */
TableRow tr = new TableRow(this);
tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
/* Create a Button to be the row-content. */
Button b = new Button(this);
b.setText("Add row");
b.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
/* Add Button to row. */
tr.addView(b);
/* Add row to TableLayout. */
tl.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.FILL_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
}
View changed to this:
<TableRow
android:id="#+id/copyRow"
android:layout_width="fill_parent" >
android:stretchColumns="0,1,2"
<Spinner
android:padding="3dip"
android:gravity="left"
android:id="#+id/Spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp" />
<Spinner
android:padding="3dip"
android:gravity="left"
android:id="#+id/Spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp" />
<Spinner
android:padding="3dip"
android:gravity="left"
android:id="#+id/spinner3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp" />
</TableRow>
If It makes a difference, I'm using JellyBean 4.3 as the target API
here is solution with ListView
you can finde all source code here
Activity Class
public class MainActivity extends Activity {
private List<RowItem> rows = new ArrayList<RowItem>();
private ListView list;
private Button addButton;
private SimpleListAdapter listAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get view elements
list = (ListView)findViewById(R.id.list);
addButton = (Button)findViewById(R.id.addButton);
//lets add few items to our list, note that selection item should not exceed length of spinners item
rows.add(new RowItem(0, 0, 0));
rows.add(new RowItem(0, 1, 2));
rows.add(new RowItem(2, 1, 1));
//create adapter and assign it to your list view
listAdapter = new SimpleListAdapter(this, R.layout.list_item, rows);
list.setAdapter(listAdapter);
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
rows.add(new RowItem(0, 0, 0));
listAdapter.notifyDataSetChanged();
}
});
}
Adapter Class
public class SimpleListAdapter extends ArrayAdapter<RowItem>{
private Context context;
private int layoutResourceId;
private List<RowItem> data = null;
private ArrayList<String> spinnerArray1 = new ArrayList<String>();
private ArrayList<String> spinnerArray2 = new ArrayList<String>();
private ArrayList<String> spinnerArray3 = new ArrayList<String>();
public SimpleListAdapter(Context context, int layoutResourceId, List<RowItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
spinnerArray1.add("S1 One");
spinnerArray1.add("S1 Two");
spinnerArray1.add("S1 Three");
spinnerArray2.add("S2 One");
spinnerArray2.add("S2 Two");
spinnerArray2.add("S2 Three");
spinnerArray3.add("S3 One");
spinnerArray3.add("S3 Two");
spinnerArray3.add("S3 Three");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ItemHolder holder;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ItemHolder();
holder.Spinner1 = (Spinner)row.findViewById(R.id.Spinner1);
holder.Spinner2 = (Spinner)row.findViewById(R.id.Spinner2);
holder.Spinner3 = (Spinner)row.findViewById(R.id.Spinner3);
//add adapter to spinners so that there is something to select from
ArrayAdapter<String> spinnerArrayAdapter1 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_dropdown_item, spinnerArray1);
holder.Spinner1.setAdapter(spinnerArrayAdapter1);
ArrayAdapter<String> spinnerArrayAdapter2 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_dropdown_item, spinnerArray2);
holder.Spinner2.setAdapter(spinnerArrayAdapter2);
ArrayAdapter<String> spinnerArrayAdapter3 = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_dropdown_item, spinnerArray3);
holder.Spinner3.setAdapter(spinnerArrayAdapter3);
row.setTag(holder);
}
else
{
holder = (ItemHolder)row.getTag();
}
final RowItem rowItem = data.get(position);
holder.Spinner1.setSelection(rowItem.getSelectionIndex1());
holder.Spinner2.setSelection(rowItem.getSelectionIndex2());
holder.Spinner3.setSelection(rowItem.getSelectionIndex3());
holder.Spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(context, "you selected an item from spinner 1", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
return row;
}
class ItemHolder{
Spinner Spinner1;
Spinner Spinner2;
Spinner Spinner3;
}
simple model
public class RowItem {
private int selectionIndex1;
private int selectionIndex2;
private int selectionIndex3;
public RowItem(int selectionIndex1, int selectionIndex2, int selectionIndex3) {
super();
this.selectionIndex1 = selectionIndex1;
this.selectionIndex2 = selectionIndex2;
this.selectionIndex3 = selectionIndex3;
}
public int getSelectionIndex1() {
return selectionIndex1;
}
public void setSelectionIndex1(int selectionIndex1) {
this.selectionIndex1 = selectionIndex1;
}
public int getSelectionIndex2() {
return selectionIndex2;
}
public void setSelectionIndex2(int selectionIndex2) {
this.selectionIndex2 = selectionIndex2;
}
public int getSelectionIndex3() {
return selectionIndex3;
}
public void setSelectionIndex3(int selectionIndex3) {
this.selectionIndex3 = selectionIndex3;
}
}
View items: Main view
<LinearLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:orientation="vertical"
android:gravity="center" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:dividerHeight="5dp"/>
<Button
android:id="#+id/addButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Add Item"
/>
item renderer for list view
<?xml version="1.0" encoding="utf-8"?>
<Spinner
android:id="#+id/Spinner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="left"
android:padding="3dip" />
<Spinner
android:id="#+id/Spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="left"
android:padding="3dip" />
<Spinner
android:id="#+id/Spinner3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="left"
android:padding="3dip" />

Categories

Resources