Getting error in Counter in Android - java

Following is my code. I need to get the increment value in FloatingActionButton. I've written the code.
activity_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: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="database.fab.MainActivity">
<ListView
android:id="#+id/lvListView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/rel1" >
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/rlRelativeLayout"
android:layout_margin="16dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" >
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="65dp"
android:layout_height="65dp"
android:layout_gravity="bottom|end"
android:src="#mipmap/cart_main"
android:clickable="true"
android:scaleType="fitXY"
android:onClick="fab" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/null_value_zero"
android:id="#+id/fab_text"
android:textColor="#42b138"
android:layout_marginTop="23dp"
android:layout_centerHorizontal="true"
android:textStyle="bold"
android:textSize="17sp"
android:elevation="7dp" />
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>
custom_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_margin="16dp"
android:background="#FFFFFF"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="140dp">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginStart="20dp"
android:layout_marginLeft="20dp"
android:layout_centerVertical="true"
android:id="#+id/ivImageViewMain"/>
<ImageView
android:layout_width="120dp"
android:layout_height="80dp"
android:id="#+id/CounterImage"
android:src="#mipmap/main_add"
android:layout_marginRight="20dp"
android:layout_marginEnd="20dp"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
</RelativeLayout>
</RelativeLayout>
MainActivity.java
package database.fab;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
ListView lvListView;
ImageView CounterImage;
TextView fab_text;
Adapter adapter;
int counter = 0;
int[] images_item = {
R.mipmap.apple,
R.mipmap.blackberry,
R.mipmap.cherry,
R.mipmap.coconut,
R.mipmap.grapes,
R.mipmap.orange,
R.mipmap.peach,
R.mipmap.pineapple,
R.mipmap.pomegranate,
R.mipmap.banana
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lvListView = (ListView) findViewById(R.id.lvListView);
fab_text = (TextView) findViewById(R.id.fab_text);
ImageView imageView= (ImageView) findViewById(R.id.CounterImage);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
fab_text.setText(String.valueOf(counter));
}
});
adapter = new Adapter(getApplicationContext(), R.layout.custom_listview);
lvListView.setAdapter(adapter);
int i = 0;
for (int Image : images_item){
Helper helper = new Helper(images_item[i]);
adapter.add(helper);
i++;
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
}
}
Adapter.java
package database.fab;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
public class Adapter extends ArrayAdapter {
List arrayList = new ArrayList();
public Adapter(Context context, int resource) {
super(context, resource);
}
int counter;
public void add(Helper object) {
super.add(object);
arrayList.add(object);
}
static class ImageHolder{
ImageView img_item;
}
#Override
public int getCount() {
return this.arrayList.size();
}
#Override
public Object getItem(int position) {
return this.arrayList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
view = convertView;
ImageHolder imageHolder;
if (convertView == null) {
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.custom_listview, parent, false);
imageHolder = new ImageHolder();
imageHolder.img_item = (ImageView) view.findViewById(R.id.ivImageViewMain);
view.setTag(imageHolder);
}
else {
imageHolder = (ImageHolder) view.getTag();
}
Helper h;
h = (Helper) this.getItem(position);
imageHolder.img_item.setImageResource(h.getImage_item());
return (view);
}
}
Helper.java
package database.fab;
public class Helper {
private int image_item;
public Helper(int image_item) {
this.image_item = image_item;
}
public int getImage_item() {
return image_item;
}
public void setImage_item(int image_item) {
this.image_item = image_item;
}
}
Error
12-21 13:01:00.535 13336-13336/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: database.fab, PID: 13336
java.lang.RuntimeException: Unable to start activity ComponentInfo{database.fab/database.fab.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2308)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2368)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1285)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5233)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at database.fab.MainActivity.onCreate(MainActivity.java:42)
at android.app.Activity.performCreate(Activity.java:6001)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2368) 
at android.app.ActivityThread.access$800(ActivityThread.java:144) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1285) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.app.ActivityThread.main(ActivityThread.java:5233) 
at java.lang.reflect.Method.invoke(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:372) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693) 
I need to get the increment value in FloatingActionButton after I press the add image. Don't know where I went wrong. Please help me with this. Thanks in advance.

Update: revert this, I missed the second ImageView - sry
change this:
ImageView imageView= (ImageView) findViewById(R.id.CounterImage);
to:
ImageView imageView= (ImageView) findViewById(R.id.ivImageViewMain);
Update:
In your main activity you are setting the view to activity_main.xml:
setContentView(R.layout.activity_main);
Then you are trying to get the view with the ID CounterImage:
ImageView imageView = (ImageView) findViewById(R.id.CounterImage)
which does not exist in activity_main.xml
Update 2:
You should look at a few Java and Android basics.
int i = 0;
for (int Image : images_item){
Helper helper = new Helper(images_item[i]);
adapter.add(helper);
i++;
}
You are mixing two for-loops here.
This:
for(int image : images_item) {
adapter.add(new Helper(image));
}
would be a nicer way to do the same thing.
Update 3:
You are inflating the correct layout in Adapter.java:
view = layoutInflater.inflate(R.layout.custom_listview, parent, false);
Right there you can add a OnClickListener:
ImageView imageView= (ImageView) view.findViewById(R.id.CounterImage);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
fab_text.setText(String.valueOf(counter));
}
});
Don't forget to remove the false code from the Activity.

Related

Android Studio Grid View doesn't show when I run the app

I created a Java class that should display something like this:
But this is what I get when I run the app:
It doesn't show what I wanted and Android Studio doesn't show any error in Logcat, so I don't know why it's not working.
This is the code for the class SetsActivity:
package com.example.myquiz;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.widget.GridView;
import android.widget.Toolbar;
public class SetsActivity extends AppCompatActivity {
private GridView sets_grid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sets);
androidx.appcompat.widget.Toolbar toolbar = findViewById(R.id.set_toolbar);
//setSupportActionBar(toolbar);
String title = getIntent().getStringExtra("CATEGORY");
getSupportActionBar().setTitle(title);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
sets_grid = findViewById(R.id.sets_gridview);
SetsAdapter adapter = new SetsAdapter(2);
sets_grid.setAdapter(adapter);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if(item.getItemId() == android.R.id.home)
{
SetsActivity.this.finish();
}
return super.onOptionsItemSelected(item);
}
}
I also created an adapter class SetsAdapter so I'm gonna post the code for it as well:
package com.example.myquiz;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class SetsAdapter extends BaseAdapter {
private int numOfSets;
public SetsAdapter(int numOfSets) {
this.numOfSets = numOfSets;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.set_item_layout, parent, false);
} else {
view = convertView;
}
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(parent.getContext(),QuestionActivity.class);
parent.getContext().startActivity(intent);
}
});
((TextView) view.findViewById(R.id.setNo_tv)).setText(String.valueOf(position + 1));
return view;
}
}
And here is the code for the XML file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
tools:context=".SetsActivity"
android:orientation="vertical">
<androidx.appcompat.widget.Toolbar
android:id="#+id/set_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark"
></androidx.appcompat.widget.Toolbar>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sets"
android:textSize="26sp"
android:textStyle="bold"
android:padding="16dp" />
<GridView
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="#+id/sets_gridview"
android:layout_weight="1"
android:gravity="center"
android:horizontalSpacing="16dp"
android:verticalSpacing="16dp"
android:padding="16dp"
android:columnWidth="100dp"
android:numColumns="auto_fit"
></GridView>
</LinearLayout>
Here is the code for the XML file set_item_layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="100dp"
android:layout_height="100dp"
android:orientation="vertical"
android:gravity="center"
android:background="#drawable/round_corner"
android:backgroundTint="#FFC3C3"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="1"
android:id="#+id/setNo_tv"
android:textStyle="bold"
android:textColor="#android:color/black"
android:textSize="45sp"></TextView>
</LinearLayout>
The getCount() method in the SetsAdapter should return numOfSets not 0.
#Override
public int getCount() {
return numOfSets;
}

Android ViewPager.PagerTransformer Cube animation strange behavior

I am trying to implement a cube animation on my viewPager. The animation looks good on the emulator and a Samsung S8 device, but on Huawei P10 Android 7.0 it looks like in the image below:
I don't understand why the image is cropped on my Huawei device. Below is my code:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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"
tools:context="ro.helpproject.funcode.help.MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
view_pager_item.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/imageView_mario"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#android:color/black"
android:src="#drawable/mario" />
CubeTransformer.java class
package ro.helpproject.funcode.help;
import android.support.v4.view.ViewPager;
import android.view.View;
public class CubeTransformer implements ViewPager.PageTransformer {
#Override
public void transformPage(View view, float position) {
view.setPivotX(position <= 0 ? view.getWidth(): 0.0f);
view.setRotationY(90f * position);
}
}
MainActivity.java
package ro.helpproject.funcode.help;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MyViewPagerAdapter adapter = new MyViewPagerAdapter();
ViewPager pager = findViewById(R.id.pager);
pager.setPageTransformer(true, new CubeTransformer());
pager.setAdapter(adapter);
}
protected class MyViewPagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return 3;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
ImageView imageView = (ImageView) inflater.inflate(R.layout.view_pager_item, container, false);
container.addView(imageView);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
}
}
How can I fix the issue?
imageview.setAdjustViewBounds(true);
imageview.setFitToScreen(true);
imageview.setScaleType(ScaleType.FIT_XY);
update.....
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/imageView_mario"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:scaleType="fitXY"
android:background="#android:color/black"
android:src="#drawable/mario" />
The best way to achieve this is to add a parent to your imageView as follows:
<?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="horizontal"
android:gravity="center">
<ImageView
android:id="#+id/imageView_mario"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/black"
android:src="#drawable/mario" />
</LinearLayout>
Then in instantiateItem replace imageView with the LinearLayout:
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
LinearLayout linearLayout = (LinearLayout) inflater.inflate(R.layout.view_pager_item, container, false);
container.addView(linearLayout);
return linearLayout;
}
This should work properly.
The reason that your solution does not work is that the viewpager tries to fill it's "pages" with the imageview that you provide from your xml, and so it is stretched and has unexpected behaviour.

How to add the ListView element to be referenced in the individual Activity files

The app crashes as soon as any of the list Activities are launched:
NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter' on a null object reference
My instructor says its happening because the layouts haven't been configured correctly. Right now, the list_item is being inflated as the Activity layout. Please create a separate layout, such as activity_list and add the ListView element there to be referenced in the individual Activity files
Here's the code
MainActivity
package com.example.tourguide;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button event = (Button) findViewById(R.id.events);
Button mall = (Button) findViewById(R.id.malls);
Button resturant = (Button) findViewById(R.id.resturants);
Button university = (Button) findViewById(R.id.uinversities);
event.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent event = new Intent(MainActivity.this, events.class);
startActivity(event); }
});
mall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mall = new Intent(MainActivity.this, malls.class);
startActivity(mall);
}
});
resturant.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent resturant = new Intent(MainActivity.this, resturants.class);
startActivity(resturant);
}
});
university.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent university = new Intent(MainActivity.this, universities.class);
startActivity(university);
}
});
}}
WordAdapter.java
package com.example.tourguide;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class WordAdapter extends ArrayAdapter<listitem> {
public WordAdapter(Activity context, ArrayList<listitem> listitems) {
super(context, 0, listitems);
}
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
listitem currentItem = getItem(position);
TextView name = (TextView) listItemView.findViewById(R.id.text1);
name.setText(currentItem.getName());
ImageView image = (ImageView) listItemView.findViewById(R.id.image1);
image.setImageResource(currentItem.getImage());
TextView dist = (TextView) listItemView.findViewById(R.id.text2);
dist.setText(currentItem.getDist());
TextView price = (TextView) listItemView.findViewById(R.id.text2);
price.setText(currentItem.getPrice());
return listItemView;
}
}
listitem.java
package com.example.tourguide;
import android.widget.ImageView;
public class listitem {
private String name="";
private int image;
private String dist="";
private String price="";
public listitem(String namea, int imagea, String dista, String pricea){
name = namea;
imagea = image;
dist= dista;
price=pricea;
}
/*********** Set Methods ******************/
public void setName(String name)
{
this.name = name;
}
public void setImage(int image)
{
this.image = image;
}
public void setDist(String dist)
{
this.dist = dist;
}
public void setPrice(String price)
{
this.price = price;
}
/*********** Get Methods ****************/
public String getName()
{
return this.name;
}
public int getImage()
{
return this.image;
}
public String getDist()
{
return this.dist;
}
public String getPrice()
{
return this.price;
}
}
Univerisities.java
package com.example.tourguide;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.ListView;
import java.util.ArrayList;
public class universities extends Activity {
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.list_item);
ArrayList<listitem> listitemArrayList = new ArrayList<listitem>();
listitemArrayList.add(new listitem("Prince Sultan University", R.drawable.u1, "AlNarjes Dist", "$"));
listitemArrayList.add(new listitem("Princess Nourah University", R.drawable.u2, "AlNarjes Dist", "$"));
listitemArrayList.add(new listitem("King Saud University", R.drawable.u3, "AlNarjes Dist", "$"));
WordAdapter adapter = new WordAdapter(this, listitemArrayList);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
tools:context="com.example.tourguide.MainActivity"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="29sp"
android:textColor="#3DC195"
android:textAlignment="center"
android:text="Tour Guide App" />
<TextView
android:id="#+id/text2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#6AA13F"
android:textSize="18sp"
android:text="Tour Guide App is designed to help you discover Riyadh city sightseeings including events, malls, resturants and universities.the app will be developed periodically to add more features... stay tuned" />
<Button
android:id="#+id/events"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Events"
android:onClick="onClickEvent"/>
<Button
android:id="#+id/malls"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Malls"
android:onClick="onClickMall"/>
<Button
android:id="#+id/resturants"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Resturants"
android:onClick="onClickRest"/>
<Button
android:id="#+id/uinversities"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Universities"
android:onClick="onClickUniv"/>
</LinearLayout>
activity_list.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">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
list_item.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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<ImageView
android:id="#+id/image1"
android:layout_width="163dp"
android:layout_height="96dp"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="68dp"
android:layout_marginTop="30dp"
android:orientation="vertical">
<TextView
android:id="#+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#DB0BA4"
android:textSize="20sp"
/>
<TextView
android:id="#+id/text2"
android:layout_width="113dp"
android:layout_height="wrap_content"
android:textColor="#456233"
android:textSize="15sp"
/>
<TextView
android:id="#+id/text3"
android:layout_width="113dp"
android:layout_height="wrap_content"
android:textColor="#C1B03D"
android:textSize="15sp"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
In the file Univerisities.java you should change your layout file to activity_list.xml.
Line
setContentView(R.layout.list_item);
Must be changed to :
setContentView(R.layout.activity_list);
Bro,
First you are trying to inflate the ListView item into you activity, which is wrong:
Change the setContentView(R.layout.list_item) to setContentView(R.layout.activity_list);
Also please check out the ViewHolder pattern for ListView's since the your adapter's getView method should be improved by that to make scrolling even more smooth:
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
and if no items are appearing in the list, you should also override the getItemCount on adatpterto return the size of the list.

Android - Listview in Fragment

I want to create a ListView in Fragment but something goes wrong.
In layout listmygroups.xml are three TextViews (trainermygroupslistwhen, trainermygroupslistwhere, trainermygroupslistname).
I try to open fragment with listview(TrainerMyGroups) from another fragment by:
getFragmentManager().beginTransaction().replace(R.id.MainContainer,new TrainerMyGroups()).addToBackStack(null).commit();
TrainerMyGroups.java:
package com.hgyghyfghyu.apkana40;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
/**
* A simple {#link Fragment} subclass.
*/
public class TrainerMyGroups extends Fragment {
ListView listView;
TrainerGroupsAdapter adapter;
String when[]={"tak","ret","sd"};
String where[]={"dsf","sdf","sdfsdf"};
String name[]={"sdfsdf","xcvxcv","xcvxcv"};
public TrainerMyGroups() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_trainer_my_groups, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listView = (ListView) getActivity().findViewById(R.id.trainermygroupslistview);
adapter = new TrainerGroupsAdapter(getContext(),R.layout.list_mygroups);
for(int i=0;i<3;i++){
TrainerGroupsDataProvider dataprovider = new TrainerGroupsDataProvider(when[i],name[i],where[i]);
adapter.add(dataprovider);
}
listView.setAdapter(adapter);
}
}
TrainerGroupsAdapter.java:
package com.hgyghyfghyu.apkana40;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
import java.util.ArrayList;
/**
* Created by dd on 2016-04-04.
*/
public class TrainerGroupsAdapter extends ArrayAdapter {
List list = new ArrayList();
public TrainerGroupsAdapter(Context context, int resource) {
super(context, resource);
}
static class Datahandler{
TextView name;
TextView when;
TextView where;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return this.list.size();
}
#Override
public Object getItem(int position) {
return this.list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row=convertView;
Datahandler handler;
if(convertView==null){
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row= inflater.inflate(R.layout.list_mygroups,parent,false);
handler = new Datahandler();
handler.name = (TextView) row.findViewById(R.id.trainermygroupslistname);
handler.where = (TextView) row.findViewById(R.id.trainermygroupslistwhere);
handler.when = (TextView) row.findViewById(R.id.trainermygroupslistwhen);
row.setTag(handler);
}
else {
handler = (Datahandler)row.getTag();
}
TrainerGroupsDataProvider dataProvider;
dataProvider = (TrainerGroupsDataProvider)this.getItem(position);
handler.name.setText(dataProvider.getName());
handler.when.setText(dataProvider.getWhen());
handler.where.setText(dataProvider.getWhere());
return row;
}
}
and there is error from AndroidMonitor
FATAL EXCEPTION: main
Process: com.hgyghyfghyu.apkana40, PID: 27778
java.lang.NullPointerException
at com.hgyghyfghyu.apkana40.TrainerMyGroups.onCreate(TrainerMyGroups.java:41)
at android.support.v4.app.Fragment.performCreate(Fragment.java:1951)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1029)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5045)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
line 41 from TrainerMyGroups is
listView.setAdapter(adapter);
I am not sure but probably this solution works only in Activity, not in Fragment, How can I change my code to make it workable?
element list 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="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="5">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/trainermygroupslistwhen"
android:textStyle="bold"
android:textSize="20sp"
android:textColor="#FFFFFF"
android:layout_centerInParent="true"/>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/trainermygroupslistname"
android:textStyle="bold"
android:textSize="10sp"
android:textColor="#FFFFFF"
android:layout_centerInParent="true"/>
</RelativeLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="3">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/trainermygroupslistwhere"
android:textStyle="bold"
android:textSize="10sp"
android:textColor="#FFFFFF"
android:layout_centerInParent="true"/>
</RelativeLayout>
</LinearLayout>
</LinearLayout>
You should add some data before set the adapter:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
listView = (ListView) getActivity().findViewById(R.id.trainermygroupslistview);
adapter = new TrainerGroupsAdapter(getContext(),R.layout.list_mygroups);
for(int i=0;i<3;i++){
TrainerGroupsDataProvider dataprovider = new TrainerGroupsDataProvider(when[i],name[i],where[i]);
adapter.add(dataprovider);
}
listView.setAdapter(adapter);
}

java.lang.OutOfMemoryError when displaying CollapsingToolbarLayout in my android app?

Am having trouble displaying CollapsingToolbarLayout in my android application. Would somebody please tell me where am going wrong... After running the application, I got this log
adroidRuntime: FATAL EXCEPTION: main
java.lang.OutOfMemoryError
at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:502)
at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:355)
at android.graphics.BitmapFactory.decodeResource(BitmapFactory.java:378)
at android.graphics.BitmapFactory.decodeResource(BitmapFactory.java:408)
at com.android.epepea.epepea.GPS.dynamicToolBarColor(GPS.java:108)
at com.android.epepea.epepea.GPS.onCreate(GPS.java:91)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
activity that am using to display the CollapsingToolbarLayout looks like this:
package com.android.epepea.epepea;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.graphics.Palette;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.GoogleMap;
import java.util.ArrayList;
public class GPS extends AppCompatActivity {
private UserData userData;
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private ActionBarDrawerToggle toggle;
private DrawerLayout drawerLayout;
private LinearLayout linearLayout;
private TextView userName;
private TextView userEmail;
private ArrayList<Items> items = new ArrayList<>();
private CollapsingToolbarLayout collapsingToolbarLayout;
private ImageView header;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
recyclerView = (RecyclerView) findViewById(R.id.login_recycler);
layoutManager = new LinearLayoutManager(this);
toggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close);
drawerLayout.addDrawerListener(toggle);
// native objects;
userName = (TextView) findViewById(R.id.text_view_name);
userEmail = (TextView) findViewById(R.id.text_view_email);
linearLayout = (LinearLayout) findViewById(R.id.navigation);
adapter = new LoginUserAdpter(this, items, getSupportFragmentManager(), drawerLayout, linearLayout);
setUpRecyclerView();
// classes
userData = new UserData(this);
String userNameSet = userData.getFirstName() + " " + userData.getSecondName();
userName.setText(userNameSet);
userEmail.setText(userData.getEmail());
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
collapsingToolbarLayout.setTitle("Epepea Gps");
//header = (ImageView) findViewById(R.id.collapsing_image);
dynamicToolBarColor();
toolBarTextAppearance();
final Intent intent = new Intent(this, Maps.class);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab_oepn_maps);
assert fab != null;
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(intent);
}
});
}
private void dynamicToolBarColor() {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_background_123);
Palette.from(bitmap).generate(new Palette.PaletteAsyncListener() {
#Override
public void onGenerated(Palette palette) {
collapsingToolbarLayout.setContentScrimColor(palette.getMutedColor(R.attr.colorPrimaryDark));
collapsingToolbarLayout.setStatusBarScrimColor(palette.getMutedColor(R.attr.colorPrimaryDark));
}
});
}
private void toolBarTextAppearance() {
collapsingToolbarLayout.setCollapsedTitleTextAppearance(R.style.AppTheme);
collapsingToolbarLayout.setExpandedTitleTextAppearance(R.style.AppTheme_AppBarOverlay);
}
private void unbindDrawables(View view) {
if (view.getBackground() != null) {
view.getBackground().setCallback(null);
}
if (view instanceof ViewGroup) {
for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
unbindDrawables(((ViewGroup) view).getChildAt(i));
}
((ViewGroup) view).removeAllViews();
}
}
// Call this method from onDestroy()
public void onDestroy() {
super.onDestroy();
unbindDrawables(findViewById(R.id.drawer));
System.gc();
}
private void setUpRecyclerView() {
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
String[] menuText = this.getResources().getStringArray(R.array.menu_text_array);
int menuImages[] = {
R.drawable.ic_stay_current_portrait_white_24dp,
R.drawable.ic_language_white_24dp,
R.drawable.ic_contact_mail_white_24dp,
R.drawable.ic_build_white_24dp,
R.drawable.ic_person_outline_white_24dp,
R.drawable.ic_receipt_white_24dp,
R.drawable.ic_exit_to_app_white_24dp
};
for (int i = 0; i < menuText.length && i < menuImages.length; i++) {
items.add(new Items(
menuText[i],
menuImages[i]
));
}
recyclerView.setAdapter(adapter);
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(linearLayout)) {
drawerLayout.closeDrawer(linearLayout);
} else {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Confirm Close")
.setMessage("Are you sure you want to close app?")
.setCancelable(false)
.setPositiveButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
exitApp();
}
})
.setNegativeButton("Cancel", null)
.show();
}
}
public void exitApp() {
super.finish();
}
#Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
toggle.syncState();
}
#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_main, 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;
}
if (id == android.R.id.home) {
if (drawerLayout.isDrawerOpen(linearLayout))
drawerLayout.closeDrawer(linearLayout);
else
drawerLayout.openDrawer(linearLayout);
}
return super.onOptionsItemSelected(item);
}
}
My Xml Layout looks like this:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
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:id="#+id/drawer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.android.epepea.epepea.GPS">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar"
android:layout_width="match_parent"
android:layout_height="250dp"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<ImageView
android:id="#+id/collapsing_image"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/ic_background_123"
android:fitsSystemWindows="true"
android:scaleType="centerCrop"
app:layout_collapseMode="parallax" />
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_gps" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab_oepn_maps"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_pin_drop_white_36dp"
app:layout_anchor="#id/app_bar_layout"
app:layout_anchorGravity="bottom|right|end" />
</android.support.design.widget.CoordinatorLayout>
<LinearLayout
android:id="#+id/navigation"
android:layout_width="280dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/system_color"
android:orientation="vertical">
<!-- some content comes here -->
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_marginBottom="5dp"
android:background="#drawable/ic_background_nice_kitkat"
android:padding="15dp">
<TextView
android:id="#+id/text_view_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/image_profile"
android:layout_marginBottom="10dp"
android:gravity="center"
android:padding="7dp"
android:text="Benson Karue"
android:textAppearance="?android:textAppearanceMedium"
android:textColor="#fff"
android:textStyle="bold" />
<ImageView
android:id="#+id/image_profile"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_centerInParent="true"
android:src="#drawable/ic_account_circle_white_48dp" />
<TextView
android:id="#+id/text_view_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/image_profile"
android:layout_marginTop="10dp"
android:gravity="center"
android:padding="7dp"
android:text="bensonkarue30#gmail.com"
android:textAppearance="?android:textAppearanceSmall"
android:textColor="#000"
android:textStyle="bold" />
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginBottom="15dp"
android:background="#e1e1e1" />
<android.support.v7.widget.RecyclerView
android:id="#+id/login_recycler"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="5dp"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
Would appreciate too much if I get somebody to assist me. Regards.
At this line:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_background_123);
you are decoding high resolution image. In order to manage that with a library you can use one of these:
Glide
picasso
or if you want to generate palette by picasso first read this article
Picassopalette
is another library you can use to generate palette by picasso.
or you can use this code for glide:
Glide.with(this)
.load(your image path,id,...)
.asBitmap()
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
Palette.Builder palette = Palette.from(resource);
palette.generate(new Palette.PaletteAsyncListener() {
#Override
public void onGenerated(Palette palette) {
}
});
}
});

Categories