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;
}
}
Related
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
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
I'm newbie and just study Java around 1 month.
i'm trying to create group picture by grid view and if i click any picture then show for user alert dialog ask user want to delete picture or not. But somehow when i try to set event for grid view by image. i can't start up app. can help me find where is crash cause app can't start up.
package com.example.hi.gridviewhinhanh;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<Danhsachhinhanh> manghinhanh;
HinhanhAdapter arrayAdapter;
GridView gridView;
ImageView imgView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = findViewById(R.id.gridview);
manghinhanh = new ArrayList<>();
manghinhanh.add(new Danhsachhinhanh(R.drawable.chupanh));
manghinhanh.add(new Danhsachhinhanh(R.drawable.goidien));
manghinhanh.add(new Danhsachhinhanh(R.drawable.photoshop));
manghinhanh.add(new Danhsachhinhanh(R.drawable.quality));
manghinhanh.add(new Danhsachhinhanh(R.drawable.secutiry));
manghinhanh.add(new Danhsachhinhanh(R.drawable.signuptoday));
arrayAdapter = new HinhanhAdapter(MainActivity.this, manghinhanh);
gridView.setAdapter(arrayAdapter);
imgView = findViewById(R.id.imageviewHinhanh);
imgView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder hopthoai = new AlertDialog.Builder(MainActivity.this);
hopthoai.setTitle("Do you want to delete");
hopthoai.setMessage("Please confirm");
hopthoai.setIcon(R.mipmap.ic_launcher);
hopthoai.setCancelable(false);
hopthoai.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
hopthoai.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "You choose No", Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
package com.example.hi.gridviewhinhanh;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
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.BaseAdapter;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
public class HinhanhAdapter extends BaseAdapter {
Context context;
ArrayList<Danhsachhinhanh> danhsachhinhanhArrayList;
public HinhanhAdapter (Context context, ArrayList<Danhsachhinhanh> danhsachhinhanhArrayList){
this.context = context;
this.danhsachhinhanhArrayList = danhsachhinhanhArrayList;
}
#Override
public int getCount() {
return danhsachhinhanhArrayList.size();
}
#Override
public Object getItem(int position) {
return danhsachhinhanhArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.dong_item_gridviewhinhanh,null);
ImageView imageView = convertView.findViewById(R.id.imageviewHinhanh);
Danhsachhinhanh danhsachhinhanh = (Danhsachhinhanh) getItem(position);
imageView.setImageResource(danhsachhinhanh.getHinhanh());
return convertView;
}
}
place you imageView clickListener in Adapter's getView() and check it again.
Becuase your imageView does not exist there. For more information read about adapter and recycleview.
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()
Hi am using a "Add" button in ActionBar of my app on clicking it a ListView gets open and the user can tap on any list item to add that item to the RecyclerView which is the parent activity(MainActivity holding the Recyclerview) but on exiting the app the last added item stays on MainActivity's view. I guess SharedPreferences' Editor is getting overwritten everytime. Can you please help in providing some snippet as i can't call editor.put() method multiple times as the click happens on listView. My RecyclerView contains an image and a text.
Here is my MainActivity's Code
package com.example.mohitmehndiratta.customlistadap;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Icon;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import static android.support.v7.widget.LinearLayoutManager.*;
public class MainActivity extends AppCompatActivity {
public static ArrayList<DataSet> alist;
int i;
RecyclerView rv;
static RecycledAdap adap;
static String args;
static int rid;
static SharedPreferences sharedPreferences;
public static void addnow(String arg)
{
args=arg;
rid=R.drawable.i;
alist.add(new DataSet(args,rid));
adap.notifyDataSetChanged();
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putInt("Iconid",rid);
editor.putString("AppName",args);
editor.apply();
if (sharedPreferences!=null)
{
int x=sharedPreferences.getInt("Iconid",rid);
String y=sharedPreferences.getString("AppName",args);
addnow(y);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.new_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.addbtn)
{
Intent intent=new Intent(this,AppList.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences("MyPrefs",getApplicationContext().MODE_PRIVATE);
rv=(RecyclerView)findViewById(R.id.rv);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
rv.setLayoutManager(mLayoutManager);
rv.setItemAnimator(new DefaultItemAnimator());
rv.addItemDecoration(new ItemDecoration(this, LinearLayoutManager.VERTICAL));
for(i=0;i<DataModel.name.length;i++) {
alist = new ArrayList<DataSet>();
alist.add(new DataSet("Paytm",R.drawable.i));
alist.add(new DataSet("Facebook",R.drawable.i1));
alist.add(new DataSet("ShareIt",R.drawable.i2));
alist.add(new DataSet("Instagram",R.drawable.i3));
alist.add(new DataSet("BookMyShow",R.drawable.i4));
}
adap=new RecycledAdap(getApplicationContext(),alist);
rv.setAdapter(adap);
MyListener mlistener=new MyListener(getApplicationContext(),rv, new MyListener.ReClickListener() {
#Override
public void onClick(int position) {
Toast.makeText(getApplicationContext(),"Launching item"+position,Toast.LENGTH_SHORT).show();
LauncherHandler lh=new LauncherHandler(position);
String pkname=lh.getpack();
AppDialog adialog=new AppDialog();
adialog.packagenameset(pkname);
adialog.show(getFragmentManager(),"AppDialogFrag");
}
#Override
public void onLongClick(int position) {
LauncherHandler lh=new LauncherHandler(position);
String pkname=lh.getpack();
Toast.makeText(getApplicationContext(),"Launching item"+position,Toast.LENGTH_SHORT).show();
AppDialog adialog=new AppDialog();
adialog.packagenameset(pkname);
adialog.show(getFragmentManager(),"AppDialogFrag");
}
});
rv.addOnItemTouchListener(mlistener);
if (sharedPreferences!=null)
{
int x=sharedPreferences.getInt("Iconid",rid);
String y=sharedPreferences.getString("AppName",args);
addnow(y);
}
else
{
Toast.makeText(getApplication(),"There is nothing in app's cache",Toast.LENGTH_SHORT).show();
}
}
}
ListView code :
package com.example.mohitmehndiratta.customlistadap;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class AppList extends AppCompatActivity {
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_list);
PackageManager pm=getPackageManager();
ArrayList<ApplicationInfo> li= (ArrayList<ApplicationInfo>) pm.getInstalledApplications(0);
ArrayList al=new ArrayList<String>();
String str;
String strpk;
ApplicationInfo info;
for(int i=0;i<li.size();i++)
{
info=li.get(i);
str=info.loadLabel(pm).toString();
Drawable appicon=info.loadIcon(pm);
al.add(str);
}
lv=(ListView)findViewById(R.id.listView);
final ArrayAdapter adap=new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item,al);
lv.setAdapter(adap);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String text=lv.getItemAtPosition(i).toString();
Toast.makeText(getApplicationContext(),text+i,Toast.LENGTH_SHORT).show();
MainActivity.addnow(text);
}
});
}
}