Fatal error in casting constraint view to text view - java

I am new to android development and am trying to workaround with some installed applications in my app. The problem is that am getting some casting error
(android.support.constraint.ConstraintLayout cannot be cast to android.widget.TextView)
I have referred to many posts here and i tried to figured out but no luck with that. As a last try I am posting my code here, hoping a response.
The entire code is posted below`.
Any help would be appreciated
ApplicationAdapter.java
package e.nani.myapplication;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.util.List;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
public class ApplicationAdapter extends ArrayAdapter<ApplicationInfo > {
private int resourceLayout;
private Context mContext;
List<ApplicationInfo> items;
PackageManager pm ;
ApplicationInfo p;
public ApplicationAdapter(Context context, int resource, List<ApplicationInfo> items) {
super(context, resource, items);
this.resourceLayout = resource;
this.mContext = context;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (null == view) {
LayoutInflater layoutInflater = (LayoutInflater) mContext
.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.row_view, null);
}
pm=mContext.getPackageManager();
p = items.get(position);
if (p!= null) {
ImageView tt1 = (ImageView)view.findViewById(R.id.img);
TextView tt2= (TextView)view.findViewById(R.id.t1);
if (tt1 != null) {
tt1.setImageDrawable(p.loadIcon(pm));
}
if (tt2 != null) {
tt2.setText(p.packageName);
}
}
return view;
}
}
MainActivity.java
package e.nani.myapplication;
import android.annotation.SuppressLint;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.util.List;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ListView listview;
ApplicationAdapter<ApplicationInfo> adapter;
List<ApplicationInfo> ls=new ArrayList<>();
PackageManager pm;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.lists);
try {
pm= getPackageManager();
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo packageInfo : packages) {
ls.add(packageInfo);
adapter = new ApplicationAdapter<ApplicationInfo>(this, R.layout.row_view, ls);
listview.setAdapter(adapter);
Log.i("added", String.valueOf(pm.getClass().getName()));
Log.i("middle",packageInfo.packageName);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="#+id/lists"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />
</android.widget.RelativeLayout>
row_view.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="#+id/t1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<TextView
android:id="#+id/t2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<ImageView
android:id="#+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</android.support.constraint.ConstraintLayout>
``the crash report
Caused by: java.lang.ClassCastException: android.support.constraint.ConstraintLayout cannot be cast to android.widget.TextView
at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:432)
at android.widget.ArrayAdapter.getView(ArrayAdapter.java:415) 
at e.nani.myapplication.ApplicationAdapter.getView(ApplicationAdapter.java:49) 
at android.widget.AbsListView.obtainView(AbsListView.java:2408) 
at android.widget.ListView.makeAndAddView(ListView.java:2126) 
at android.widget.ListView.fillDown(ListView.java:851) 
at android.widget.ListView.fillDown(ListView.java:833) 
at android.widget.ListView.fillFromTop(ListView.java:921) 
at android.widget.ListView.layoutChildren(ListView.java:1900) 
at android.widget.AbsListView.onLayout(AbsListView.java:2207) 
at android.view.View.layout(View.java:20831) 
at android.view.ViewGroup.layout(ViewGroup.java:6203) 
at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1083) 
at android.view.View.layout(View.java:20831) 
at android.view.ViewGroup.layout(ViewGroup.java:6203) 
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323) 
at android.widget.FrameLayout.onLayout(FrameLayout.java:261) 
at android.view.View.layout(View.java:20831) 
at android.view.ViewGroup.layout(ViewGroup.java:6203) 
at android.support.v7.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:444) 
at android.view.View.layout(View.java:20831) 
at android.view.ViewGroup.layout(ViewGroup.java:6203) 
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323) 
at android.widget.FrameLayout.onLayout(FrameLayout.java:261) 
at android.view.View.layout(View.java:20831) 
at android.view.ViewGroup.layout(ViewGroup.java:6203) 
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1812) 
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1656) 
at android.widget.LinearLayout.onLayout(LinearLayout.java:1565) 
at android.view.View.layout(View.java:20831) 
at android.view.ViewGroup.layout(ViewGroup.java:6203) 
at android.widget.FrameLayout.layoutChildren(FrameLayout.java:323) 
at android.widget.FrameLayout.onLayout(FrameLayout.java:261) 
at com.android.internal.policy.DecorView.onLayout(DecorView.java:754) 
at android.view.View.layout(View.java:20831) 
at android.view.ViewGroup.layout(ViewGroup.java:6203) 
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2991) 
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2504) 
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1635) 
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7795) 
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1172) 
at android.view.Choreographer.doCallbacks(Choreographer.java:984) 
at android.view.Choreographer.doFrame(Choreographer.java:809) 
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1158) 
at android.os.Handler.handleCallback(Handler.java:873) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6863) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 

Try to use ViewHolder pattern:
static class ViewHolder {
ImageView tt1;
TextView tt2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder holder;
if (null == view) {
LayoutInflater layoutInflater = (LayoutInflater) mContext.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
view = layoutInflater.inflate(R.layout.row_view, null);
holder = new ViewHolder();
holder.tt1 = (ImageView)view.findViewById(R.id.img);
holder.tt2 = (TextView)view.findViewById(R.id.t1);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
pm = mContext.getPackageManager();
p = items.get(position);
if (p != null) {
holder.tt1.setImageDrawable(p.loadIcon(pm));
holder.tt2.setText(p.packageName);
}
return view;
}
Useful link:
https://stackoverflow.com/a/3832467/10995239

Related

Getting all launchable apps on home like android home menu with bottom dots

Hi i am working on a custom launcher app.I want to get all launchable apps on home like this.
My Current Code:
MainActivity.class
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import java.util.Collections;
import java.util.List;
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycalview);
LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(this);
StaggeredGridLayoutManager mGridLayoutManager = new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL); // 2 is number of items per row
recyclerView.setLayoutManager(mGridLayoutManager); // deafult
PackageManager pm = this.getPackageManager();
Intent main = new Intent(Intent.ACTION_MAIN, null);
main.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> launchables = pm.queryIntentActivities(main, 0);
Collections.sort(launchables,
new ResolveInfo.DisplayNameComparator(pm));
Adapter adapter = new Adapter(this, launchables, pm);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(mGridLayoutManager);
}
}
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"
tools:context=".MainActivity2">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycalview"
android:layout_below="#+id/battery"
android:layout_width="match_parent"
android:layout_above="#id/hi"
android:layout_height="match_parent" />
</RelativeLayout>
Adapter.java
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
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.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder> {
List<ResolveInfo> lapps;
Context context;
PackageManager pm=null;
public Adapter(Context context, List<ResolveInfo> apps, PackageManager pn) {
this.context = context;
lapps=apps;
pm=pn;
}
#NonNull
#Override
public Adapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.griditem, parent, false);
Adapter.ViewHolder viewHolder = new Adapter.ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull Adapter.ViewHolder holder, #SuppressLint("RecyclerView") int position) {
holder.images.setImageDrawable(lapps.get(position).loadIcon(pm));
holder.text.setText(lapps.get(position).loadLabel(pm));
holder.itemlayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ResolveInfo launchable = lapps.get(position);
ActivityInfo activity = launchable.activityInfo;
ComponentName name = new ComponentName(activity.applicationInfo.packageName,
activity.name);
Intent i = new Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_LAUNCHER);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
i.setComponent(name);
context.startActivity(i);
}
});
}
#Override
public int getItemCount() {
return lapps.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView images;
TextView text;
RelativeLayout itemlayout;
public ViewHolder(View view) {
super(view);
images = (ImageView) view.findViewById(R.id.icon);
text = (TextView) view.findViewById(R.id.label);
itemlayout=view.findViewById(R.id.item);
}
}
}
griditem.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/item"
android:layout_marginTop="5dp"
android:gravity="center"
android:layout_height="wrap_content">
<com.google.android.material.imageview.ShapeableImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:id="#+id/icon"
android:theme="#style/Theme.RoundedImage"/>
<TextView
android:layout_width="60dp"
android:layout_height="20dp"
android:layout_marginTop="5dp"
android:layout_below="#id/icon"
android:gravity="center_horizontal"
android:textSize="15dp"
android:textColor="#color/white"
android:textStyle="bold"
android:id="#+id/label"/>
</RelativeLayout>
I just want to show all apps on home screen with horizontal scroll with bottom dots.
I have also try this method but my issue can't solved

ListView with custom adapter is crashing after adding a new item? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Custom ListView Adapter Null Object Reference
(1 answer)
Closed 2 years ago.
I'm creating an app that makes inventaries for the restaurant of my parents. I've been working in the custom view that shows the name of the product and the quantity of it on the current inventary in a listView. Everything works fine until I add a new product to any inventary. After I add the product any time that I go to the that inventary the app crash.
This is visionInventario.java
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class visionInventario extends AppCompatActivity {
TextView tituloInventario;
static int positionCurrentInventario;
static InventarioListAdapter adapter1;
public void loadData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences",MODE_PRIVATE);
Gson gson = new Gson();
String json = sharedPreferences.getString("task list",null);
Type type = new TypeToken<ArrayList<Inventario>>(){}.getType();
Inventarios.InventariosActuales = gson.fromJson(json,type);
for(int i = 0; i < Inventarios.InventariosActuales.size();i++){
Inventarios.nombresInventarios.add(Inventarios.InventariosActuales.get(i).nombre);
}
if(Inventarios.InventariosActuales == null){
Inventarios.InventariosActuales = new ArrayList<>();
}
}
public void saveData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(Inventarios.InventariosActuales);
editor.putString("task list",json);
editor.apply();
}
public void addProductoButton(View view){
Intent goToAddNewProducto = new Intent(this,addNewProducto.class);
startActivity(goToAddNewProducto);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vision_inventario);
//loadData();
tituloInventario = (TextView) findViewById(R.id.tituloInventario);
Intent thisIntent = getIntent();
positionCurrentInventario = thisIntent.getIntExtra("itemPosition",0);
tituloInventario.setText(Inventarios.nombresInventarios.get(positionCurrentInventario));
ListView listProductos = (ListView) findViewById(R.id.listaProductos);
adapter1 = new InventarioListAdapter(this,Inventarios.InventariosActuales.get(positionCurrentInventario).products);
listProductos.setAdapter(adapter1);
listProductos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent goToVisionProducto = new Intent(getApplicationContext(),visionProducto.class);
goToVisionProducto.putExtra("productPosition",position);
startActivity(goToVisionProducto);
}
});
}
}
This is addNewProducto.java
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
public class addNewProducto extends AppCompatActivity {
TextView nombreDelNuevoProducto;
public void saveData(){
SharedPreferences sharedPreferences = getSharedPreferences("shared preferences",MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(Inventarios.InventariosActuales);
editor.putString("task list",json);
editor.apply();
}
public void AddNewProductoClick(View view){
producto nuevoProducto = new producto(nombreDelNuevoProducto.getText().toString());
Inventarios.InventariosActuales.get(visionInventario.positionCurrentInventario).addProduct(nuevoProducto);
visionInventario.adapter1.notifyDataSetChanged();
Toast.makeText(this,"¡Producto añadido!", Toast.LENGTH_SHORT).show();
saveData();
finish();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_new_producto);
nombreDelNuevoProducto = (TextView) findViewById(R.id.nombreProducto);
}
}
This is InventarioListAdapter.java
package com.DreamFactory.restaurantcontrol;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import org.w3c.dom.Text;
import java.util.ArrayList;
import java.util.List;
public class InventarioListAdapter extends BaseAdapter {
Context context;
ArrayList<producto> arr;
public InventarioListAdapter(Context context, ArrayList<producto> arr) {
this.context = context;
this.arr = arr;
}
#Override
public int getCount() {
return arr.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(context).inflate(R.layout.adapter_view_layout, parent, false);
}
TextView quantity = (TextView)convertView.findViewById(R.id.existenciasInventarioVision);
TextView nameQ = (TextView) convertView.findViewById(R.id.productoInventarioVision);
quantity.setText(arr.get(position).cantidad);
nameQ.setText(arr.get(position).nombre);
return listItemView;
}
}
This is adapter_view_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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">
<LinearLayout
android:layout_width="409dp"
android:layout_height="729dp"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<TextView
android:id="#+id/productoInventarioVision"
android:gravity="center"
android:textAlignment="center"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_weight="66.6"
android:text="TextView" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="33.3"
android:orientation="vertical">
<TextView
android:id="#+id/existenciasInventarioVision"
android:layout_width="match_parent"
android:layout_height="61dp"
android:gravity="center"
android:text="TextView" />
</LinearLayout>
</LinearLayout>
</androidx.constraintlayout.widget.ConstrainLayout>
This is my LogCat when it crashes
2020-04-05 22:49:14.310 17301-17301/com.DreamFactory.restaurantcontrol E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.DreamFactory.restaurantcontrol, PID: 17301
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.DreamFactory.restaurantcontrol.InventarioListAdapter.getView(InventarioListAdapter.java:52)

How to Save İmage from ViewPager?

My problem is that it always saves the same photo when I press the Save Button. I have more than 10 photos in my Viewpager, it just saves the first one, so I can't save what I want the photo,
I want to save the open photo.
I want the photo in the open window to be saved.
items.xml
<?xml version="1.0" encoding="utf-8" ?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/gallery_root"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="#+id/layut"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true"
android:orientation="vertical"
android:weightSum="30">
<FrameLayout
android:id="#+id/wallpaper_preview_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/movie_image"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</LinearLayout>
</RelativeLayout>
fragment_simple.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"
tools:context=".Fragment.SimpleFragment">
<androidx.viewpager.widget.ViewPager
android:id="#+id/vivi_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<Button
android:id="#+id/bSave"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_alignParentTop="true"
android:layout_marginStart="15dp"
android:gravity="center"
android:layout_marginTop="150dp"
android:text="Save"
android:layout_alignParentStart="true"
android:textSize="24sp"
android:padding="0dp" />
</RelativeLayout>
SimpleFragment.java
package com.example.duvarlar.Fragment;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.example.duvarlar.Adapters.MyAdapter;
import com.example.duvarlar.Listeneer.IFirebaseLoadDone;
import com.example.duvarlar.Models.Movie;
import com.example.duvarlar.R;
import com.example.duvarlar.Transformer.DeptPageTransformer;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* A simple {#link Fragment} subclass.
*/
public class SimpleFragment extends Fragment implements IFirebaseLoadDone, ValueEventListener {
ViewPager viewPager;
MyAdapter adapter;
DatabaseReference movies;
IFirebaseLoadDone iFirebaseLoadDone;
Button save;
OutputStream outputStream;
public SimpleFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_simple, container, false);
movies = FirebaseDatabase.getInstance().getReference("Sports");
iFirebaseLoadDone = this;
loadMovie();
viewPager = (ViewPager) view.findViewById(R.id.vivi_pager);
save = (Button) view.findViewById(R.id.bSave);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewPager.setDrawingCacheEnabled(true);
Bitmap bitmap = viewPager.getDrawingCache();
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/Android");//directory name of your choice
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = "Photo-" + n + ".jpg";
File file = new File(newDir, fotoname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
Toast.makeText(getActivity(), "Saved to your folder" + fotoname, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
}
}
});
return view;
}
private void loadMovie() {
movies.addValueEventListener(this);
}
#Override
public void onFirebaseLoadSuccess(List<Movie> movieList) {
adapter = new MyAdapter(getContext(), movieList);
viewPager.setAdapter(adapter);
}
#Override
public void onFirebasLoadFailed(String message) {
Toast.makeText(getContext(), "" + message, Toast.LENGTH_SHORT).show();
}
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
List<Movie> movieList = new ArrayList<>();
for (DataSnapshot moviesSnapShot : dataSnapshot.getChildren())
movieList.add(moviesSnapShot.getValue(Movie.class));
iFirebaseLoadDone.onFirebaseLoadSuccess(movieList);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
iFirebaseLoadDone.onFirebasLoadFailed(databaseError.getMessage());
}
#Override
public void onDestroy() {
movies.removeEventListener(this);
super.onDestroy();
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onStop() {
movies.removeEventListener(this);
super.onStop();
}
}
MyAdapter.java
package com.example.duvarlar.Adapters;
import android.app.WallpaperManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.example.duvarlar.Models.Movie;
import com.example.duvarlar.R;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
public class MyAdapter extends PagerAdapter {
Context context;
List<Movie> movieList;
LayoutInflater inflater;
OutputStream outputStream;
public MyAdapter(Context context, List<Movie> movieList) {
this.context = context;
this.movieList = movieList;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return movieList.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
((ViewPager)container).removeView((View)object);
}
#NonNull
#Override
public Object instantiateItem(#NonNull final ViewGroup container, final int position) {
final View view = inflater.inflate(R.layout.items,container,false);
final ImageView movie_image = (ImageView)view.findViewById(R.id.movie_image);
Picasso.get()
.load(movieList.get(position).getImage())
.fit()
.centerCrop()
.into(movie_image);
container.addView(view);
return view;
}
}

How can i show running app icon in listview using ActivityManager and PackageManager?

I'm trying to making a app that..
-shows currently running app icons in listview
-click item on listview that shows running app icons to switch
But i don't know how to do these, and i already googled a lot
but i found that i should use ActivityManager.RunningTaskinfo and Packagemanager to do these
Cloud you help me to do these?
How can i show running app icons in listview and give listview click event(such as OnItemClick)that switch to app which is clicked on listview?
[LeftSidePanel.java]
package kr.hybdms.sidepanel;
import java.util.ArrayList;
import java.util.List;
import kr.hybdms.sidepanel.PanelArrayAdapter;
import kr.hybdms.sidepanel.R;
import kr.hybdms.sidepanel.util.SystemUiHider;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*
* #see SystemUiHider
*/
public class LeftSidePanel extends Activity implements
OnItemClickListener {
ListView listView;
List<PanelItemDetail> rowItems;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_left_side_panel);
List<PackageInfo> packs = getPackageManager().getInstalledPackages(10);
Drawable[] images = new Drawable[packs.size()];
for(int i=0;i<packs.size();i++) {
PackageInfo p = packs.get(i);
images[i]= p.applicationInfo.loadIcon(getPackageManager());
}
rowItems = new ArrayList<PanelItemDetail>();
listView = (ListView) findViewById(R.id.panelcontents);
PanelArrayAdapter adapter = new PanelArrayAdapter(this,
R.layout.panelrow, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
[PanelArrayAdapter.java]
package kr.hybdms.sidepanel;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
public class PanelArrayAdapter extends ArrayAdapter<PanelItemDetail> {
Context context;
public PanelArrayAdapter(Context context, int resourceId,
List<PanelItemDetail> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
PanelItemDetail rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.panelrow, null);
holder = new ViewHolder();
holder.imageView = (ImageView) convertView.findViewById(R.id.appicon);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.imageView.setImageDrawable(rowItem.getImageId());
return convertView;
}
}
[PanelItemDetail.java]
package kr.hybdms.sidepanel;
import android.graphics.drawable.Drawable;
public class PanelItemDetail {
private Drawable imageId;
public PanelItemDetail(Drawable images) {
this.imageId = images;
}
public Drawable getImageId() {
return imageId;
}
public void setImageId(Drawable imageId) {
this.imageId = imageId;
}
}
[panelrow.xml]
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/appicon"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_margin="10dp" />
</RelativeLayout>
[activity_left_side_panel.xml]
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".LeftSidePanel" >
<ImageView android:id="#+id/transparentbackground"
android:src="#drawable/detector"
android:adjustViewBounds="true"
android:gravity="center_vertical"
android:scaleType="fitXY"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_x="0dp"
android:layout_y="0dp"
android:layout_marginLeft="100dp"/>
<ImageView
android:id="#+id/panelbackground"
android:layout_width="100dp"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:scaleType="fitXY"
android:src="#drawable/panelbg" />
<ListView
android:id="#+id/panelcontents"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignRight="#+id/panelbackground"
android:layout_centerVertical="true"
android:listSelector="#drawable/panel_item_bg"
android:divider="#000000" >
</ListView>
</RelativeLayout>
Try going through this tutorial it may help you
here!

custom ImageViews disapearing from ListAdapter

Ok, my problem is similar to this Background image in ListView entries spontaneously disappearing
but this issue is resolved with using setImageResource on a normal ImageView but I want an animation to exist on all elements of a list, and this can not be done without a custom ImageView class that allows the animation to run. Does anyone know why these images are disappearing after scrolling in the list view and maybe how this can be fixed? Thanks a lot!
Here is my ListAdapter:
package com.mmgworldwide.layout.listadapters;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import com.mmgworldwide.R;
import com.mmgworldwide.customviews.SpinLoadingAnim;
import com.mmgworldwide.data.FWREvent;
import com.mmgworldwide.data.ImageThreadLoader;
import com.mmgworldwide.data.ImageThreadLoader.ImageLoadedListener;
import com.mmgworldwide.layout.ListDivider;
import com.mmgworldwide.data.Personality;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class PersonalityListAdapter extends ArrayAdapter<Object>{
private Context parentContext;
public ArrayList<Object> items_list_ref;
private ImageThreadLoader imageLoader = new ImageThreadLoader();
public PersonalityListAdapter(Context context, int resource, int textViewResourceId, ArrayList<Object> items_list) {
super(context, resource, textViewResourceId, items_list);
items_list_ref = items_list;
parentContext = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Object node = (Object) items_list_ref.get(position);
LayoutInflater inflater = (LayoutInflater) parentContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(node instanceof ListDivider){
//make new div bar
View div = inflater.inflate(R.layout.list_bar, parent, false);
TextView div_label = (TextView) div.findViewById(R.id.div_label);
div_label.setText(((ListDivider) node).label.toUpperCase());
return div;
}
View row = inflater.inflate(R.layout.picture_list, parent, false);
TextView name_txt = (TextView) row.findViewById(R.id.name_txt);
TextView title_txt = (TextView) row.findViewById(R.id.title_txt);
final ImageView portrait_img = (ImageView) row.findViewById(R.id.portrait);
final ImageView load_cnt = (ImageView) row.findViewById(R.id.portrait_loadDisplay);
name_txt.setText(((Personality) node).getName());
SpannableString title_underlined = new SpannableString(((Personality) node).getTitle());
title_underlined .setSpan(new UnderlineSpan(), 0, title_underlined.length(), 0);
title_txt.setText(title_underlined);
load_cnt.setVisibility(View.VISIBLE);
return row;
}
Here is my custom ImageView class
package com.mmgworldwide.customviews;
import android.R;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.AnimationDrawable;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;
public class SpinLoadingAnim extends ImageView{
AnimationDrawable animation;
private final Integer FRAME_SPEED = 20;
public SpinLoadingAnim(Context context, AttributeSet attrs){
super(context, attrs);
//setBackgroundColor(Color.GREEN);
animation = new AnimationDrawable();
animation.addFrame(context.getResources().getDrawable(com.mmgworldwide.R.drawable.spinner_00000), FRAME_SPEED);
animation.addFrame(context.getResources().getDrawable(com.mmgworldwide.R.drawable.spinner_00001), FRAME_SPEED);
animation.addFrame(context.getResources().getDrawable(com.mmgworldwide.R.drawable.spinner_00002), FRAME_SPEED);
animation.addFrame(context.getResources().getDrawable(com.mmgworldwide.R.drawable.spinner_00003), FRAME_SPEED);
animation.setOneShot(false);
this.setBackgroundDrawable(animation);
this.post(new Starter());
}
class Starter implements Runnable {
public void run() {
animation.start();
}
}
And here is my layout 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="wrap_content"
android:background="#FFFFFF"
android:gravity="center_vertical"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp">
<ImageView android:layout_width="60dp" android:layout_height="60dp" android:id="#+id/portrait" android:layout_centerVertical="true"></ImageView>
<com.mmgworldwide.customviews.SpinLoadingAnim
android:id="#+id/portrait_loadDisplay"
android:layout_width="20dp" android:layout_height="20dp"
android:background="#939598"
android:layout_centerVertical="true" android:layout_marginLeft="20dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" />
<ImageView android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_centerVertical="true" android:id="#+id/arrow" android:src="#drawable/list_arrow" android:layout_alignParentRight="true"></ImageView>
<LinearLayout android:layout_toRightOf="#id/portrait" android:layout_toLeftOf="#id/arrow" android:layout_centerVertical="true" android:orientation="vertical" android:layout_height="wrap_content" android:layout_width="wrap_content" android:baselineAligned="true" android:paddingLeft="15dp" android:paddingRight="15dp">
<TextView android:text="CHEF NAME" android:id="#+id/name_txt" android:layout_width="wrap_content" android:textColor="#000000" android:textStyle="bold"
android:layout_height="wrap_content" android:paddingBottom="2dp" android:textSize="15sp"></TextView>
<TextView android:text="Chef Title" android:id="#+id/title_txt" android:layout_width="wrap_content" android:textColor="#000000"
android:layout_height="wrap_content" android:textSize="13sp"></TextView>
</LinearLayout>
</RelativeLayout>
Every 5th 'preloader' graphic is still disappearing, but thanks Michele this has helped a lot, and made things cleaner.
package com.mmgworldwide.layout;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.mmgworldwide.R;
import com.mmgworldwide.data.DataConnection;
import com.mmgworldwide.data.ImageThreadLoader;
import com.mmgworldwide.data.Personality;
//http://code.google.com/p/and-conference/source/browse/trunk/src/com/totsp/conference/PresentationList.java
public class Personalities extends Activity{
private ListView listView;
private ArrayAdapter<Object> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.personalities);
listView = (ListView) findViewById(R.id.personalitylistview);
listView.setDrawingCacheEnabled(false);
addListAdapter();
setFooterView("more");
}
private void addListAdapter(){
ArrayList<Object> adaptList = makeAdaptList();
adapter = new PersonalityListAdapter(this, 0, adaptList);
listView.setAdapter(adapter);
}
private ArrayList<Object> makeAdaptList(){
ArrayList<Object> adaptList = new ArrayList<Object>();
String currentDivDate = " ";
for(Personality aEvent : DataConnection.fwrInfo.getPersonalityList()){
adaptList.add(aEvent);
}
return adaptList;
}
private void setFooterView(String highlight){
Footer footer = (Footer) findViewById(R.id.footer);
footer.setHighlight(highlight);
}
//***********************************************************************************************************************************************
//ViewHolder
//***********************************************************************************************************************************************
static class ViewHolder {
private TextView tView1;
private TextView tView2;
private ImageView iView1;
}
//***********************************************************************************************************************************************
//PersonalityListAdapter
//***********************************************************************************************************************************************
private class PersonalityListAdapter extends ArrayAdapter<Object>{
LayoutInflater vi = (LayoutInflater) Personalities.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
private Context parentContext;
public ArrayList<Object> items_list_ref;
private ImageThreadLoader imageLoader = new ImageThreadLoader();
public PersonalityListAdapter(final Context context, final int resId, final ArrayList<Object> presentations) {
super(context, resId, presentations);
this.items_list_ref = presentations;
parentContext = context;
}
#Override
public int getCount() {
return items_list_ref.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//Log.d("TROY", "adding view");
View v = convertView;
if (v == null) {
//Log.d("TROY", "inflation");
v = vi.inflate(R.layout.picture_list, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.tView1 = (TextView) v.findViewById(R.id.name_txt);
viewHolder.tView2 = (TextView) v.findViewById(R.id.title_txt);
viewHolder.iView1 = (ImageView) v.findViewById(R.id.portrait);
v.setTag(viewHolder);
}
Object p = items_list_ref.get(position);
if (p != null) {
//Log.d("TROY", "setting stuff");
ViewHolder viewHolder = (ViewHolder) v.getTag();
viewHolder.tView1.setText("hi");
}
return v;
}
}
}
Here is a screen shot of what's going on (why is the 5th preload graphic not showing?):
edit ------
Ok, I added the getCount and getItemId overrides but still have the same issues, I figured I would start a project from scratch and try again with just a listView, same issue, I have put up a test project to demonstrate this frustrating issue. In this test I did not even add any data to the adapters, and the animation only works for some of them, just like with my master project.
Thank you so much for your patience and help this far Michele, you have been very awesome.
http://faceonfire.com/temp/ListTester.zip
ListViews are highly optimized Datastructures. You should use ViewHolders to obey the rules of Lists and make the life of the system a bit easier.
When you Scroll a ListView the System caches the Items in Holders for performance.
Read How to load the Listview "smoothly" in android
you can also try to set
yourListView.setDrawingCacheEnabled(false);
edit: ok than try to set your animation with xml
http://developer.android.com/reference/android/graphics/drawable/AnimationDrawable.html
like:
<!-- Animation frames are wheel0.png -- wheel5.png files inside the
res/drawable/ folder -->
<animation-list android:id="selected" android:oneshot="false">
<item android:drawable="#drawable/wheel0" android:duration="50" />
<item android:drawable="#drawable/wheel1" android:duration="50" />
<item android:drawable="#drawable/wheel2" android:duration="50" />
<item android:drawable="#drawable/wheel3" android:duration="50" />
<item android:drawable="#drawable/wheel4" android:duration="50" />
<item android:drawable="#drawable/wheel5" android:duration="50" />
</animation-list>
edit2: please try to implement getCount and getItemId, theres something wrong with the boundarys of your List, maybe android cant find out on with position the list is after scrolling. Oh and can you please test it with random data, not the same item all the way (perhaps some weird hash (default getItemId Implementation?) that is always the same with the same item content).
for example like this:
#Override
public int getCount() {
return <yourdatastructure>.getSize();
}
#Override
public long getItemId(int position) {
return position;
}

Categories

Resources