Problem with fragment communication(Attempt to invoke virtual method) - java

I have a tabbed activity with 2 fragments. I'm trying to transmit a string from the first fragment to the second fragment but I'm getting NULL POINTER EXCEPTION.
Here is the MainActivity.java:
package com.example.myapplication;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import com.example.myapplication.ui.main.SectionsPagerAdapter;
public class MainActivity extends AppCompatActivity implements Frag1.Exchange {
private static final String TAG = "MainActivity";
private SectionsPagerAdapter sectionsPagerAdapter;
private ViewPager viewPager;
private TabLayout tabLayout;
private void setupViewPager(ViewPager viewPager){
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
sectionsPagerAdapter.addFragment(new Frag1(), "FirstTab");
sectionsPagerAdapter.addFragment(new Frag2(), "SecondTab");
viewPager.setAdapter(sectionsPagerAdapter);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.view_pager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
#Override
public void stringExchange(String s) {
Frag2 frag2 = (Frag2) getSupportFragmentManager().findFragmentByTag("SecondTab");
frag2.displayExchange(s);
}
}
Here is SectionsPagerAdapter.java
package com.example.myapplication.ui.main;
import android.content.Context;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import com.example.myapplication.R;
import java.util.ArrayList;
import java.util.List;
/**
* A [FragmentPagerAdapter] that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> stringList = new ArrayList<>();
public void addFragment(Fragment fragment, String title){
fragmentList.add(fragment);
stringList.add(title);
}
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a (defined as a static inner class below).
return fragmentList.get(position);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return stringList.get(position);
}
#Override
public int getCount() {
// Show 2 total pages.
return fragmentList.size();
}
}
Here is Frag1.java:
package com.example.myapplication;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
public class Frag1 extends Fragment{
private static final String TAG = "FirstTab";
private Button transfer;
private Exchange ex;
public interface Exchange{
public void stringExchange(String s);
}
#Nullable
#Override
public View onCreateView(#NonNull final LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.tab1_fragment, container, false);
transfer = (Button) view.findViewById(R.id.button2);
ex = (Exchange) getActivity();
transfer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s = "Test";
ex.stringExchange(s);
}
});
return view;
}
}
With its xlm tab1_fragment.xlm:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:id="#+id/tab1"
>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/transfer"
android:layout_centerInParent="true"/>
</RelativeLayout>
And finally here is the Frag2.java:
package com.example.myapplication;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import java.util.ArrayList;
public class Frag2 extends Fragment {
private static final String TAG = "SecondTab";
private ListView listView;
private ArrayList<String> arrayList = new ArrayList<>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab2_fragment, container, false);
listView = (ListView) view.findViewById(R.id.list_view);
ArrayAdapter arrayAdapter = new ArrayAdapter(getContext(),android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(arrayAdapter);
return view;
}
public void displayExchange(String s){
arrayList.add(s);
}
}
I think the problem is in MainActivity when I call findFragmentByTag("SecondTab") because it's tag is not set to SecondTab but i don't know how to set it.
Any help will be apreciated!

Use ViewModel to share data between fragments. Refer: https://developer.android.com/topic/libraries/architecture/viewmodel.html#sharing

Related

null obejct reference error on setAdapter

I have Tried to set an adapter for my recycler view and it throws me the following error
Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference
this is the code for current activty
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.widget.TextView;
public class resourcetab extends AppCompatActivity {
private TextView txt;
private DataModel2 data =new DataModel2();
private RecyclerView recyclerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resourcetab);
data =getIntent().getParcelableExtra("object");
resourceadapter adapter = new resourceadapter(data);
recyclerView.setAdapter(adapter);
}
}
the code for recycler view adapter
package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class resourceadapter extends RecyclerView.Adapter<resourceadapter.ViewHolder> {
private List<String> URL= new ArrayList<>();
private List<String> type=new ArrayList<>();
private List<String> Giver=new ArrayList<>();
public resourceadapter(DataModel2 data){
this.URL=data.URL;
this.type=data.type;
this.Giver=data.Giver;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.each_resource , parent , false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
URL.get(position);
holder.type1.setText(type.get(position));
holder.name1.setText(Giver.get(position));
holder.liner.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
#Override
public int getItemCount() {
return Giver.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private LinearLayout liner ;
private TextView type1;
private TextView name1;
public ViewHolder(#NonNull View itemView) {
super(itemView);
liner = itemView.findViewById(R.id.liner);
name1 = itemView.findViewById(R.id.textView6);
type1 = itemView.findViewById(R.id.textView7);
}
}
}
You have to initialize your recycler view by findViewById method befor setting adapter in onCreate.
Like,
recyclerView = findViewById(R.id.recView) //id of Recycler View which you given in your xml

Images not loaded into gridView using Fresco

I am having trouble loading images from internet into gridView. I am using Fresco for image loading. When I run the app, it doesn't crash but does not show the images in gridView. Also, there is no error shown in logcat. I am new to Android development. Thanks in advance!
GalleryFragment.java
package com.example.android.tabswithswipes;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import com.example.android.tabswithswipes.Utils.GridImageAdapter;
import com.example.android.tabswithswipes.Utils.UniversalImageLoader;
import com.facebook.drawee.view.SimpleDraweeView;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.ArrayList;
/**
* Created by Chaitanya Shiva on 08-05-2018.
*/
public class GalleryFragment extends Activity {
private GridView gridView;
private ImageView galleryImage;
private ProgressBar mProgressBar;
private Spinner directorySpinner;
private Context mContext = GalleryFragment.this;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_gallery);
galleryImage = (SimpleDraweeView)findViewById(R.id.galleryImageView);
gridView = (GridView)findViewById(R.id.gridView);
directorySpinner = (Spinner)findViewById(R.id.spinnerDirectory);
mProgressBar = (ProgressBar)findViewById(R.id.progressBar);
mProgressBar.setVisibility(View.GONE);
ImageView closeGallery = (ImageView)findViewById(R.id.closeGallery);
closeGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
TextView nextScreen = (TextView) findViewById(R.id.tvNext);
nextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
Uri uri = Uri.parse("https://www.gstatic.com/webp/gallery/4.sm.jpg");
galleryImage.setImageURI(uri);
tempGridSetup();
}
private void setUpImageGrid(ArrayList<String> imgURLs){
GridView gridView = (GridView)findViewById(R.id.gridView);
GridImageAdapter adapter = new GridImageAdapter(mContext, R.layout.layout_grid_imageview,"", imgURLs);
gridView.setAdapter(adapter);
}
private void tempGridSetup(){
ArrayList<String> imgURLs = new ArrayList<>();
imgURLs.add("https://www.gstatic.com/webp/gallery/4.sm.jpg");
imgURLs.add("https://www.gstatic.com/webp/gallery3/1.sm.png");
imgURLs.add("https://cdn.pixabay.com/photo/2018/05/10/09/07/bleeding-heart-3387085_1280.jpg");
imgURLs.add("https://images.idgesg.net/images/article/2017/08/android_robot_logo_by_ornecolorada_cc0_via_pixabay1904852_wide-100732483-large.jpg");
imgURLs.add("https://www.androidcentral.com/sites/androidcentral.com/files/styles/xlarge_wm_brw/public/article_images/2018/03/android-p-logo-pixel-2-xl-5.jpg?itok=DB93lUGS");
imgURLs.add("https://www.androidcentral.com/sites/androidcentral.com/files/styles/xlarge_wm_brw/public/article_images/2018/03/android-p-virtual-notch.jpg?itok=EnKJzDgF");
imgURLs.add("https://www.androidcentral.com/sites/androidcentral.com/files/styles/xlarge_wm_brw/public/article_images/2018/03/samsung-galaxy-s9-plus-black-4.jpg?itok=bTitZlS_");
imgURLs.add("https://www.extremetech.com/wp-content/uploads/2017/03/smiling-android.jpg");
imgURLs.add("https://rimblogs.files.wordpress.com/2016/04/marshmallowman.png?w=800");
imgURLs.add("https://www.androidcentral.com/sites/androidcentral.com/files/topic_images/2015/android-apps-topic.png");
imgURLs.add("https://images.idgesg.net/images/article/2017/11/android-security-100741557-large.jpg");
setUpImageGrid(imgURLs);
}
}
GridImageAdapter.java
package com.example.android.tabswithswipes.Utils;
import android.content.Context;
import android.graphics.Bitmap;
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.ProgressBar;
import com.example.android.tabswithswipes.R;
import com.facebook.drawee.view.SimpleDraweeView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import java.util.ArrayList;
/**
* Created by Chaitanya Shiva on 12-05-2018.
*/
public class GridImageAdapter extends ArrayAdapter<String>{
private Context mContext;
private LayoutInflater mInflater;
private int layoutResource;
private String mAppend;
private ArrayList<String> imgURLs;
public GridImageAdapter(Context context, int layoutResource, String append, ArrayList<String> imgURLs) {
super(context, layoutResource, imgURLs);
this.mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.mContext = context;
this.layoutResource = layoutResource;
this.mAppend = append;
this.imgURLs = imgURLs;
}
private static class ViewHolder{
SimpleDraweeView image;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
/*
Viewholder build pattern (Similar to recyclerview)
*/
final ViewHolder holder;
if(convertView == null){
convertView = mInflater.inflate(layoutResource, parent, false);
holder = new ViewHolder();
holder.image = (SimpleDraweeView) convertView.findViewById(R.id.gridImageView);
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
}
String imgURL = getItem(position);
holder.image.setImageURI(imgURL);
return convertView;
}
}
layout_grid_imageview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<com.facebook.drawee.view.SimpleDraweeView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/gridImageView"
android:scaleType="centerCrop"/>
</RelativeLayout>
Here you forgot to hide the progressbar. You need to hide it when the image is loaded. You can do the following :
val controllerBuilder = Fresco.newDraweeControllerBuilder()
controllerBuilder.setUri(url)
controllerBuilder.oldController = drawee.controller
controllerBuilder.controllerListener = object : BaseControllerListener<ImageInfo>() {
override fun onFinalImageSet(id: String?, imageInfo: ImageInfo?, animatable: Animatable?) {
super.onFinalImageSet(id, imageInfo, animatable)
holder.mProgressBar.setVisibility(VISIBLE.GONE);
}
}
holder.image.controller = controllerBuilder.build()

How to implement custom listview adapter in tabbed activity?

I am trying to implement the custom list view in tabbed activity for youtube video playing app. I could not able to call custom listview adapter in fragment java class. I have tried to pass getActivity() to custom adapter but the app crashes. If any one know the solution please help me.
The java class are as follows:
HomeFragment.java
package layout;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
import in.testapp.app1.R;
public class HomeFragment extends Fragment {
static class Adapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList();
private final List<String> mFragmentTitleList = new ArrayList();
public Adapter(FragmentManager manager) {
super(manager);
}
public Fragment getItem(int position) {
return (Fragment) this.mFragmentList.get(position);
}
public int getCount() {
return this.mFragmentList.size();
}
public void addFragment(Fragment fragment, String title) {
this.mFragmentList.add(fragment);
this.mFragmentTitleList.add(title);
}
public CharSequence getPageTitle(int position) {
return (CharSequence) this.mFragmentTitleList.get(position);
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.viewpager);
setupViewPager(viewPager);
((TabLayout) view.findViewById(R.id.tablayout)).setupWithViewPager(viewPager);
return view;
}
private void setupViewPager(ViewPager viewPager) {
Adapter adapter = new Adapter(getChildFragmentManager());
adapter.addFragment(new YouTubeFragment(), "Tab 1");
adapter.addFragment(new SecondFragment(), "Tab 2");
viewPager.setAdapter(adapter);
}
}
YouTubeFragment.java
package layout;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import in.testapp.app1.AppUtils;
import in.testapp.app1.ChannelActivity;
import in.testapp.app1.CustomListAdapter;
import in.testapp.app1.R;
import in.testapp.app1.VideoDetails;
public class YouTubeFragment extends Fragment {
String TAG="MainActivity2";
ListView lvVideo;
ArrayList<VideoDetails> videoDetailsArrayList;
CustomListAdapter customListAdapter;
//{youtube_api_key} is replaced by actual key
String URL="https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UC5Eg6bkwsdCd-ZlcB3nt1dg&maxResults=25&key={youtube_api_key}";
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_you_tube, container, false);
lvVideo=(ListView)view.findViewById(R.id.videoList);
videoDetailsArrayList=new ArrayList<>();
//App crashes here in the beolw line
customListAdapter=new CustomListAdapter(getActivity(),videoDetailsArrayList);
//App crashes here in the above line
showVideo();
return view;
}
private void showVideo() {
RequestQueue requestQueue= Volley.newRequestQueue(getContext());
StringRequest stringRequest=new StringRequest(Request.Method.GET, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject=new JSONObject(response);
JSONArray jsonArray=jsonObject.getJSONArray("items");
for(int i=1;i<jsonArray.length();i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
JSONObject jsonVideoId=jsonObject1.getJSONObject("id");
JSONObject jsonsnippet= jsonObject1.getJSONObject("snippet");
JSONObject jsonObjectdefault = jsonsnippet.getJSONObject("thumbnails").getJSONObject("medium");
VideoDetails videoDetails=new VideoDetails();
String videoid=jsonVideoId.getString("videoId");
Log.e(TAG," New Video Id" +videoid);
videoDetails.setURL(jsonObjectdefault.getString("url"));
videoDetails.setVideoName(jsonsnippet.getString("title"));
videoDetails.setVideoDesc(jsonsnippet.getString("description"));
videoDetails.setVideoId(videoid);
videoDetailsArrayList.add(videoDetails);
}
lvVideo.setAdapter(customListAdapter);
customListAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
int socketTimeout = 30000;
RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
stringRequest.setRetryPolicy(policy);
requestQueue.add(stringRequest);
}
}
CustomListAdapter.java
package in.testapp.app1;
import android.app.Activity;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
import java.util.ArrayList;
public class CustomListAdapter extends BaseAdapter {
Activity activity;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private LayoutInflater inflater;
ArrayList<VideoDetails> singletons;
public CustomListAdapter(Activity activity, ArrayList<VideoDetails> singletons) {
this.activity = activity;
this.singletons = singletons;
}
public int getCount() {
return this.singletons.size();
}
public Object getItem(int i) {
return this.singletons.get(i);
}
public long getItemId(int i) {
return (long) i;
}
public View getView(int i, View convertView, ViewGroup viewGroup) {
if (this.inflater == null) {
this.inflater = (LayoutInflater) this.activity.getLayoutInflater();
// getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if (convertView == null) {
convertView = this.inflater.inflate(R.layout.videolist, null);
}
if (this.imageLoader == null) {
this.imageLoader = AppController.getInstance().getImageLoader();
}
NetworkImageView networkImageView = (NetworkImageView) convertView.findViewById(R.id.video_image);
final TextView imgtitle = (TextView) convertView.findViewById(R.id.video_title);
final TextView imgdesc = (TextView) convertView.findViewById(R.id.video_descriptio);
final TextView tvURL=(TextView)convertView.findViewById(R.id.tv_url);
final TextView tvVideoID=(TextView)convertView.findViewById(R.id.tv_videoId);
((LinearLayout) convertView.findViewById(R.id.asser)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(view.getContext(), VideoActivity.class);
intent.putExtra("videoId",tvVideoID.getText().toString());
view.getContext().startActivity(intent);
}
});
VideoDetails singleton = (VideoDetails) this.singletons.get(i);
networkImageView.setImageUrl(singleton.getURL(), this.imageLoader);
tvVideoID.setText(singleton.getVideoId());
imgtitle.setText(singleton.getVideoName());
imgdesc.setText(singleton.getVideoDesc());
return convertView;
}
}
VideoDeatils.java
package in.testapp.app1;
public class VideoDetails {
String VideoName;
String VideoDesc;
String URL;
String VideoId;
public void setVideoName(String VideoName){
this.VideoName=VideoName;
}
public String getVideoName(){
return VideoName;
}
public void setVideoDesc(String VideoDesc){
this.VideoDesc=VideoDesc;
}
public String getVideoDesc(){
return VideoDesc;
}
public void setURL(String URL){
this.URL=URL;
}
public String getURL(){
return URL;
}
public void setVideoId(String VideoId){
this.VideoId=VideoId;
}
public String getVideoId(){
return VideoId;
}
}

using bitmap with custom spinner

I used this tutorial to make a custom spinner but now I'm having a java.lang.OutOfMemoryError: Failed to allocate a 95976012 byte allocation with 16777120 free bytes and 31MB until OOMerror. I am aware that I should use bitmaps I just don't know how to include the bitmapFactory in my CustomAdapter. I have already compressed my images to sizes less than 16kb and put them in the mipmap folder because they are icons. I have also already tried
<application
android:largeHeap="true"
</application>
Here's my code :
MainActivity.java
package com.kathure.flags;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import static android.R.attr.id;
import static android.graphics.BitmapFactory.*;
import static java.security.AccessController.getContext;
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
String[] countryNames= {
"Kenya" , "Malawi", "Nigeria", "Rwanda", "Tanzania", "Uganda"
};
int [] flags = {
R.mipmap.kenyamin,R.mipmap.malawimin, R.mipmap.nigeriamin, R.mipmap.rwandamin, R.mipmap.tanzaniamin, R.mipmap.ugandamin
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.simpleSpinner);
spin.setOnItemSelectedListener(this);
CustomAdapter customAdapter=new CustomAdapter(getApplicationContext(),flags,countryNames);
spin.setAdapter(customAdapter);
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), countryNames[i], Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
CustomAdapter.java
package com.kathure.flags;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Created by kathure on 28/09/16.
*/
public class CustomAdapter extends BaseAdapter {
Context context;
int flags[];
String[] countryNames;
LayoutInflater inflter;
public CustomAdapter(Context applicationContext, int[] flags, String[] countryNames) {
this.context = applicationContext;
this.flags = flags;
this.countryNames = countryNames;
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return flags.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.custom_spinner_items, null);
ImageView icon = (ImageView) view.findViewById(R.id.imageView);
TextView names = (TextView) view.findViewById(R.id.textView);
icon.setImageResource(flags[i]);
names.setText(countryNames[i]);
return view;
}
}

ViewPager inside a Fragment (NestedFragments)

My app has the main activity with a Navigation Drawer, that allow the application to navigate between Fragments. Each item list of the navigation drawer shows a fragment.
In one of those Fragment I want a ViewPager, and here is where I got stuck. If I'm not wrong, this is a Fragment inside another Fragment (Nested Fragments) but I can't make this work.
This is the code of the fragment that contains the ViewPager
Seccion1.java
import android.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.List;
public class Seccion1 extends Fragment {
ViewPager vp;
private List<android.support.v4.app.Fragment> getFragments(){
List<android.support.v4.app.Fragment> list = new ArrayList<android.support.v4.app.Fragment>();
list.add(ModelFragment.newInstance("Hola como andas", "descriociones"));
list.add(ModelFragment.newInstance("0895452125x", "#FFFFEF59"));
list.add(ModelFragment.newInstance("22 Mart", "#FF9C63FF"));
list.add(ModelFragment.newInstance("Sak", "#72a83b"));
list.add(ModelFragment.newInstance("Android Studio", "#a83b97"));
return list;
}
//#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.seccion1, container, false);
vp = (ViewPager)rootView.findViewById(R.id.vp);
//vp.setPageTransformer(true, new RotateDownTransformer());
ControllerFragment cf = new ControllerFragment(getChildFragmentManager(), getFragments());
vp.setAdapter(cf);
return rootView;
}
}
I don't know how to fix this line:
ControllerFragment cf = new ControllerFragment(getChildFragmentManager(), getFragments());
Here the ControllerFragment code
ControllerFragment.java
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.List;
public class ControllerFragment extends FragmentPagerAdapter {
List<Fragment> fragments;
Context context;
public ControllerFragment(FragmentManager fm, List<Fragment> fragments){
super(fm);
this.fragments = fragments;
}
public Fragment getItem(int position){
return fragments.get(position);
}
public int getCount(){
return fragments.size();
}
public Object instantiateItem(View view, int position){
RelativeLayout relativeLayout = (RelativeLayout)view.inflate(context, R.layout.custom_fragment, null);
TextView tv_text = (TextView)relativeLayout.findViewById(R.id.tv_text);
TextView tv_description = (TextView)relativeLayout.findViewById(R.id.tv_description);
((ViewPager) view).addView(relativeLayout);
return relativeLayout;
}
}
Change this
import android.app.Fragment;
to
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;

Categories

Resources