Android Studio ImageView and Bitmap - java

An activity has an icon to choose Image from Files. After choosing the Image, The next activity page opens which has A button and an ImageView where the selected iimage should be displayed.
I can choose the Image but it does not show on ImageView.
I has tried Bitmap and it doesnt work. If I try to resize map and then run app, after choosing the image the app closes.
Below is the XML and Java of the activity
<?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"
tools:context=".ShowPhotoActivity">
<ImageView
android:id="#+id/imageView"
android:layout_width="196dp"
android:layout_height="219dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.497"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.414"
tools:srcCompat="#tools:sample/avatars" />
<Button
android:id="#+id/btnEdit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="EDIT PHOTO"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.773" />
</androidx.constraintlayout.widget.ConstraintLayout>
//Java of the Activity.
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.util.Base64;
import android.widget.ImageView;
import java.io.File;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.File;
public class ShowPhotoActivity extends AppCompatActivity {
ImageView myImage;
Button btnEdit;
String path = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_photo);
myImage = (ImageView) findViewById(R.id.imageView);
btnEdit = findViewById(R.id.btnEdit);
path = getIntent().getExtras().getString("path");
File imgFile = new File(path);
if (imgFile.exists()) {
Bitmap b = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
//myImage.setImageBitmap(Bitmap.createScaledBitmap(b, 40, 40, false));
myImage.setImageBitmap(b);
btnEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(ShowPhotoActivity.this, EditPhotoActivity.class);
intent.putExtra("path", path);
startActivity(intent);
}
});
}
}
public static Bitmap RotateBitmat(Bitmap source, float angle) {
Matrix matrix = new Matrix();
matrix.postRotate(angle);
return Bitmap.createBitmap(source, 0, 0, source.getWidth(), source.getHeight(), matrix, true);
}
}
I need the selected Image to be shown in the ImageView and when I click the Edit button the Image should be passed to the next activity too.

Related

Lottie Animation not working with setExitSharedElementCallback android

I am working on Android with a Lottie animation. I implemented a shared transition on Lottie from one activity to another activity. But this is not Working. What am I doing wrong in my setExitSharedElementCallback method?
MainActivity.java
package com.example.trans;
import android.app.ActivityOptions;
import android.app.SharedElementCallback;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
import com.airbnb.lottie.LottieAnimationView;
public class MainActivity extends AppCompatActivity {
LottieAnimationView lottieAnimationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lottieAnimationView = findViewById(R.id.animation_logo);
setExitSharedElementCallback(new SharedElementCallback() {
#Override
public Parcelable onCaptureSharedElementSnapshot(View sharedElement, Matrix viewToGlobalMatrix, RectF screenBounds) {
int bitmapWidth = Math.round(screenBounds.width());
int bitmapHeight = Math.round(screenBounds.height());
Bitmap bitmap = null;
if (bitmapWidth > 0 && bitmapHeight > 0) {
Matrix matrix = new Matrix();
matrix.set(viewToGlobalMatrix);
matrix.postTranslate(-screenBounds.left, -screenBounds.top);
bitmap = Bitmap.createBitmap(bitmapWidth, bitmapHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.concat(matrix);
sharedElement.draw(canvas);
}
return bitmap;
}
});
findViewById(R.id.start_animation).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(MainActivity.this, lottieAnimationView, "simple_activity_transition");
startActivity(intent, options.toBundle());
}
});
}
}
activity_main.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000"
tools:context=".MainActivity">
<Button
android:id="#+id/start_animation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/animation_logo"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="click Me" />
<com.airbnb.lottie.LottieAnimationView
android:id="#+id/animation_logo"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerInParent="true"
android:layout_centerHorizontal="true"
android:transitionName="simple_activity_transition"
app:lottie_autoPlay="true"
app:lottie_loop="false"
app:lottie_rawRes="#raw/dm"
app:lottie_renderMode="hardware"
app:lottie_speed="1.2"
tools:ignore="MissingConstraints" />
</RelativeLayout>
activityMain2.java
package com.example.trans;
import androidx.appcompat.app.AppCompatActivity;
import android.app.SharedElementCallback;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.ImageView;
import com.airbnb.lottie.LottieAnimationView;
import java.util.List;
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
setEnterSharedElementCallback(new SharedElementCallback() {
#Override
public View onCreateSnapshotView(Context context, Parcelable snapshot) {
View view = new View(context);
view.setBackground(new BitmapDrawable((Bitmap) snapshot));
return view;
}
#Override
public void onSharedElementStart(List<String> sharedElementNames,
List<View> sharedElements,
List<View> sharedElementSnapshots) {
ImageView sharedElement = findViewById(R.id.animation_logo);
for (int i = 0; i < sharedElements.size(); i++) {
if (sharedElements.get(i) == sharedElement) {
View snapshot = sharedElementSnapshots.get(i);
Drawable snapshotDrawable = snapshot.getBackground();
sharedElement.setBackground(snapshotDrawable);
sharedElement.setImageAlpha(0);
forceSharedElementLayout();
break;
}
}
}
private void forceSharedElementLayout() {
ImageView sharedElement = findViewById(R.id.animation_logo);
int widthSpec = View.MeasureSpec.makeMeasureSpec(sharedElement.getWidth(),
View.MeasureSpec.EXACTLY);
int heightSpec = View.MeasureSpec.makeMeasureSpec(sharedElement.getHeight(),
View.MeasureSpec.EXACTLY);
int left = sharedElement.getLeft();
int top = sharedElement.getTop();
int right = sharedElement.getRight();
int bottom = sharedElement.getBottom();
sharedElement.measure(widthSpec, heightSpec);
sharedElement.layout(left, top, right, bottom);
}
#Override
public void onSharedElementEnd(List<String> sharedElementNames,
List<View> sharedElements,
List<View> sharedElementSnapshots) {
ImageView sharedElement = findViewById(R.id.animation_logo);
sharedElement.setBackground(null);
sharedElement.setImageAlpha(255);
}
});
}
}
activity_main2.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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:background="#000"
android:layout_height="match_parent"
tools:context=".Main2Activity">
<com.airbnb.lottie.LottieAnimationView
android:id="#+id/animation_logo"
android:layout_marginTop="20dp"
android:layout_centerHorizontal="true"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_gravity="center"
android:scaleType="centerCrop"
android:transitionName="simple_activity_transition"
app:lottie_autoPlay="true"
app:lottie_loop="false"
app:lottie_rawRes="#raw/dm"
app:lottie_renderMode="hardware"
app:lottie_speed="1.2" />
</RelativeLayout>
Styles
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="android:windowSharedElementEnterTransition">#android:transition/explode</item>
</style>

How to display database data from an activity?

I have an android application and i want to display database data in one of the activity in a listview. I already managed to display it in a listview on a fragment, but now i want to apply the same process to an activity.
I already tried to take the code i used to display data on my fragment, and use it for my activity, but didn't work even after making some change, and i'm still getting an error on #Override.
Here is my activity code :
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.example.schoolapp.DBHelper;
import com.example.schoolapp.R;
import java.util.ArrayList;
import java.util.HashMap;
public class AdminEvenementActivity3 extends AppCompatActivity {
private TextView Date;
DBHelper SchoolDB;
String CONTENU_ANG;
String CONTENU_ANG_DATE;
HashMap<String,String> user;
ListView CDCANGList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_evenement3);
Date = (TextView) findViewById(R.id.Date);
Intent incomingIntent = getIntent();
String date = incomingIntent.getStringExtra("date");
Date.setText(date);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_cdc_ang, container, false);
CDCANGList = rootView.findViewById(R.id.CDCANGList);
SchoolDB = new DBHelper(AdminEvenementActivity3.this);
SQLiteDatabase db = SchoolDB.getReadableDatabase();
ArrayList<HashMap<String, String>> userList = new ArrayList<>();
Cursor view = db.rawQuery("SELECT CONTENU_ANGLAIS_DATE, CONTENU_ANGLAIS FROM CONTENU_COURS_ANGLAIS", null);
if (view.moveToFirst()){
do {
// Passing values
user = new HashMap<>();
CONTENU_ANG = view.getString(view.getColumnIndex("CONTENU_ANGLAIS"));
CONTENU_ANG_DATE = view.getString(view.getColumnIndex("CONTENU_ANGLAIS_DATE"));
user.put("Contenu",CONTENU_ANG);
user.put("Date",CONTENU_ANG_DATE);
userList.add(user);
} while(view.moveToNext());
Log.d("Contenu",userList.toString());
Log.d("Date",userList.toString());
ListAdapter adapter = new SimpleAdapter(AdminEvenementActivity3.this, userList, R.layout.cdcangrow,new String[]{"Contenu", "Date"}, new int[] .
{R.id.ContenuANG, R.id.ContenuANGDate});
CDCANGList.setAdapter(adapter);
}
view.close();
db.close();
return rootView;
}
}```
Here is my layout holding the listview :
```<?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">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/CDCANGList"/>
</RelativeLayout>```
And here is my layout for the arrangement of each row of the listview :
```<?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"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/ContenuANG"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:text="TextView"
app:layout_constraintStart_toEndOf="#+id/textView3"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/ContenuANGDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_marginStart="4dp"
android:layout_marginLeft="4dp"
android:layout_marginTop="24dp"
android:text="TextView"
app:layout_constraintStart_toEndOf="#+id/textView7"
app:layout_constraintTop_toBottomOf="#+id/ContenuANG" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:drawableLeft="#drawable/ic_histgeo"
android:text="Travail effectuer :"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="72dp"
android:layout_marginLeft="72dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="152dp"
android:layout_marginRight="152dp"
android:text="Date : "
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>```
I'm expecting each row of the table to display in the listview of my activity. I'm getting the following error message caused by the "#Override" : "error: method does not override or implement a method from a supertype".
'onCreateView() method is only for fragment it cannot be override in activity.'
put you all the code in onCreate() method of your activity. it will be working pretty fine Thanks
if you feel any other problem please discuss
Thanks you a lot for your answer! I did the modification, but now i'm having some troubles on my layout inflater and my retur rootView. Any ideas how i could correct this? See my code below.
package com.example.schoolapp.Admin;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.example.schoolapp.DBHelper;
import com.example.schoolapp.R;
import java.util.ArrayList;
import java.util.HashMap;
public class AdminEvenementActivity3 extends AppCompatActivity {
private TextView Date;
DBHelper SchoolDB;
String CONTENU_ANG;
String CONTENU_ANG_DATE;
HashMap<String,String> user;
ListView CDCANGList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_evenement3);
Date = (TextView) findViewById(R.id.Date);
Intent incomingIntent = getIntent();
String date = incomingIntent.getStringExtra("date");
Date.setText(date);
final View rootView = inflater.inflate(R.layout.fragment_cdc_ang, container, false);
CDCANGList = rootView.findViewById(R.id.CDCANGList);
SchoolDB = new DBHelper(AdminEvenementActivity3.this);
SQLiteDatabase db = SchoolDB.getReadableDatabase();
ArrayList<HashMap<String, String>> userList = new ArrayList<>();
Cursor view = db.rawQuery("SELECT CONTENU_ANGLAIS_DATE, CONTENU_ANGLAIS FROM CONTENU_COURS_ANGLAIS", null);
if (view.moveToFirst()){
do {
// Passing values
user = new HashMap<>();
CONTENU_ANG = view.getString(view.getColumnIndex("CONTENU_ANGLAIS"));
CONTENU_ANG_DATE = view.getString(view.getColumnIndex("CONTENU_ANGLAIS_DATE"));
user.put("Contenu",CONTENU_ANG);
user.put("Date",CONTENU_ANG_DATE);
userList.add(user);
} while(view.moveToNext());
Log.d("Contenu",userList.toString());
Log.d("Date",userList.toString());
ListAdapter adapter = new SimpleAdapter(AdminEvenementActivity3.this, userList, R.layout.cdcangrow,new String[]{"Contenu", "Date"}, new int[]{R.id.ContenuANG, R.id.ContenuANGDate});
CDCANGList.setAdapter(adapter);
}
view.close();
db.close();
return rootView;
}
}

ScrollView not scroll smoothly

I am developing online store application, i used bottom navigation menu and fragments to separate the pages of my online store , in my main fragment i have one scrollview that contains one image slider and two horizontal recycler views that used to show newest and special products.
every thing id good but
my really strange problem is that when i run application in my android phone the scrollview has really really bad performance, it scrolls really slowly and not smoothly.
i tried many ways to solve this problem ( but unfortunately none of them could solve my problem ) :
- i tried to remove image slider library
- i taught maybe images and bitmaps are the main cause of this bad performance but after i removed all images nothing changed !!!
and here is my code :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f6f6f6"
android:layoutDirection="rtl"
android:orientation="vertical">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/slider_container"
android:layout_width="wrap_content"
android:layout_height="180dp">
<com.daimajia.slider.library.SliderLayout
android:id="#+id/slider"
android:layout_width="match_parent"
android:layout_height="180dp" />
<com.daimajia.slider.library.Indicators.PagerIndicator
android:id="#+id/custom_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone" />
<com.rd.PageIndicatorView
android:id="#+id/pageIndicatorView"
app:piv_animationType="worm"
app:piv_dynamicCount="true"
app:piv_interactiveAnimation="true"
app:piv_padding="8dp"
app:piv_radius="4dp"
app:piv_selectedColor="#color/golden_vip"
app:piv_unselectedColor="#d1d1d1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="15dp" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/special_products_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_margin="10dp"
android:background="#f1f1f1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|center_vertical"
android:layout_marginRight="10dp"
android:text="محصولات ویژه وی آی پی"
android:textColor="#444444"
android:textSize="11sp"
android:textStyle="bold" />
</LinearLayout>
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:src="#drawable/volleyball" />
</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/special_products_horizontal_recyclerview"
android:layout_width="match_parent"
android:layout_height="230dp"
android:layout_below="#+id/special_products_title"
android:isScrollContainer="false"
android:nestedScrollingEnabled="false" />
<RelativeLayout
android:id="#+id/new_products_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/special_products_horizontal_recyclerview"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_margin="10dp"
android:background="#f1f1f1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right|center_vertical"
android:layout_marginRight="10dp"
android:text="محصولات جدید وی آی پی"
android:textColor="#444444"
android:textSize="11sp"
android:textStyle="bold" />
</LinearLayout>
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="20dp"
android:src="#drawable/volleyball" />
</RelativeLayout>
<android.support.v7.widget.RecyclerView
android:id="#+id/new_products_horizontal_recyclerview"
android:layout_width="match_parent"
android:layout_height="230dp"
android:layout_marginBottom="700dp"
android:layout_below="#+id/new_products_title"
android:isScrollContainer="false"
android:nestedScrollingEnabled="false" />
</LinearLayout>
</ScrollView>
<RelativeLayout
android:id="#+id/loader"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:alpha="0.3"
android:background="#222222"
android:visibility="visible">
<ProgressBar
android:id="#+id/progress_load_categories"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:indeterminate="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/progress_load_categories"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:text="لطفا منتظر بمانید ..."
android:textColor="#ffffff"
android:textStyle="bold" />
</RelativeLayout>
and here is my fragment :
package com.gladcherry.vipiranian.activityformain;
import android.app.Dialog;
import android.content.ComponentCallbacks2;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.speech.RecognizerIntent;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.daimajia.slider.library.Animations.DescriptionAnimation;
import com.daimajia.slider.library.Indicators.PagerIndicator;
import com.daimajia.slider.library.SliderLayout;
import com.daimajia.slider.library.SliderTypes.BaseSliderView;
import com.daimajia.slider.library.SliderTypes.TextSliderView;
import com.daimajia.slider.library.Tricks.ViewPagerEx;
import com.github.amlcurran.showcaseview.OnShowcaseEventListener;
import com.github.amlcurran.showcaseview.ShowcaseView;
import com.github.amlcurran.showcaseview.targets.ViewTarget;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.gladcherry.vipiranian.Adapter.CategoriesDataAdapter;
import com.gladcherry.vipiranian.Adapter.ProductsDataAdapter;
import com.gladcherry.vipiranian.MaterialSearchViewPersian;
import com.gladcherry.vipiranian.Model.CategoryModel;
import com.gladcherry.vipiranian.Model.DetailsProjectData;
import com.gladcherry.vipiranian.R;
import com.rd.PageIndicatorView;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;
import static android.app.Activity.RESULT_OK;
import static android.content.Context.MODE_PRIVATE;
/**
* Created by gladcherry on 9/30/17.
*/
public class MainViPFragment extends Fragment
implements OnShowcaseEventListener {
ViewPagerEx.OnPageChangeListener
Toolbar mToolbar;
int level = 0;
GridView gridView;
private Button inviteButton;
private static String getCategoriesApiUrl;
private Dialog loader;
private Button ChangeCity, EditProfile;
private ShowcaseView sv;
private FragmentDrawer drawerFragment;
private MaterialSearchViewPersian searchView;
private ProgressBar loadCategories;
RequestQueue queue;
TextView textView;
List<CategoryModel> SliderImages;
//private PageIndicatorView pageIndicatorView;
//private SliderLayout sliderLayout;
private RelativeLayout Loader;
private List<DetailsProjectData> specialProducts = new ArrayList<>();
private List<DetailsProjectData> newProducts = new ArrayList<>();
private ProductsDataAdapter SpecialDataAdapter;
private ProductsDataAdapter NewDataAdapter;
private RecyclerView specialRecyclerView; private RecyclerView newRecyclerView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflating view layout
View layout = inflater.inflate(R.layout.activity_store_categories, container, false);
makeJsonArrayRequest();
return layout;
}
public void createValidation(String title, String msg) {
final Dialog builder = new Dialog(getActivity(), R.style.PauseDialog);
builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
builder.setTitle(title);
builder.setContentView(R.layout.dialogforvalidations);
TextView text = (TextView) builder.findViewById(R.id.error_msg);
text.setText(msg);
Button close_dialog = (Button) builder.findViewById(R.id.close_btn_dialog);
close_dialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
builder.dismiss();
}
});
// display dialog
builder.show();
}
private void makeJsonArrayRequest() {
// Get UserId if current user has been registered or logged in
String UserIdSplash = "";
SharedPreferences prefs = getActivity().getSharedPreferences("Authentication", MODE_PRIVATE);
String userId = prefs.getString("UserName", null);
if (userId != null) {
UserIdSplash = userId;
}
// Get UserId if current user has been registered or logged in
// Get Guest Guid if Guest has been logged in as guest before
String GuidSplash = "";
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("Authentication", MODE_PRIVATE);
final String Guid = sharedPreferences.getString("Guid", null);
if (Guid != null) {
GuidSplash = Guid;
}
// Get Guest Guid if Guest has been logged in as guest before
//OSPermissionSubscriptionState status = OneSignal.getPermissionSubscriptionState();
getCategoriesApiUrl = getResources().getString(R.string.base_url);
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, getCategoriesApiUrl, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
String State = response.get("Status").toString();
if (!State.equals("1")) {
Loader.animate().alpha(0.0f).setDuration(500);
createValidation(" خطای سیستم ", response.get("Text").toString());
} else {
Loader.animate().alpha(0.0f).setDuration(500);
SliderImages = new ArrayList<>();
//pageIndicatorView.setCount(response.getJSONArray("Sliders").length());
for (int i = 0; i < response.getJSONArray("Sliders").length(); i++) {
SliderImages.add(
new CategoryModel(
response.getJSONArray("Sliders").getJSONObject(i).get("Image").toString(),
" وی آی پی | ViP ",
response.getJSONArray("Sliders").getJSONObject(i).get("Id").toString())
);
}
JSONArray SpecialProducts = response.getJSONArray("SpecialProducts");
for (int i = 0; i < SpecialProducts.length(); i++) {
JSONObject currentProduct = SpecialProducts.getJSONObject(i);
specialProducts.add(new DetailsProjectData(currentProduct.getString("Id"), currentProduct.getString("PersianName"), currentProduct.getString("Image"), currentProduct.get("UnitPrice").toString(), currentProduct.get("PriceWithDiscount").toString(), currentProduct.get("Discount").toString(), "", "", "", ""));
}
SpecialDataAdapter = new ProductsDataAdapter(getActivity(), specialProducts);
LinearLayoutManager layoutManager
= new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
specialRecyclerView = (RecyclerView) getActivity().findViewById(R.id.special_products_horizontal_recyclerview);
specialRecyclerView.setLayoutManager(layoutManager);
specialRecyclerView.setAdapter(SpecialDataAdapter);
specialRecyclerView.setNestedScrollingEnabled(false);
JSONArray NewProducts = response.getJSONArray("NewestProducts");
for (int i = 0; i < NewProducts.length(); i++) {
JSONObject currentProduct = NewProducts.getJSONObject(i);
newProducts.add(new DetailsProjectData(currentProduct.getString("Id"), currentProduct.getString("PersianName"), currentProduct.getString("Image"), currentProduct.get("UnitPrice").toString(), currentProduct.get("PriceWithDiscount").toString(), currentProduct.get("Discount").toString(), "", "", "", ""));
}
NewDataAdapter = new ProductsDataAdapter(getActivity(), newProducts);
LinearLayoutManager newlayoutManager
= new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
newRecyclerView = (RecyclerView) getActivity().findViewById(R.id.new_products_horizontal_recyclerview);
newRecyclerView.setLayoutManager(newlayoutManager);
newRecyclerView.setAdapter(NewDataAdapter);
newRecyclerView.setNestedScrollingEnabled(false);
}
}
catch (Exception ex)
{
if (ex.getMessage() != null) {
Log.d("exception", ex.getMessage());
}
Loader.animate().alpha(0.0f).setDuration(500);
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
if (error != null && error.getMessage() != null) {
Log.w("VolleyError", error.getMessage());
VolleyLog.d(this.getClass().getSimpleName(), "Error: " + error.getMessage());
}
//loadCategories.setVisibility(View.GONE);
createValidation("پیام سیستم", "لطفا اتصال اینترنت خود را بررسی نمایید .");
}
});
request.setRetryPolicy(new
DefaultRetryPolicy(10000, 1, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue = Volley.newRequestQueue(getActivity().getApplicationContext());
queue.add(request);
}
#Override
public void onShowcaseViewHide(ShowcaseView showcaseView) {
}
#Override
public void onShowcaseViewDidHide(ShowcaseView showcaseView) {
}
#Override
public void onShowcaseViewShow(ShowcaseView showcaseView) {
}
#Override
public void onShowcaseViewTouchBlocked(MotionEvent motionEvent) {
}
}
the problem was because of 2 lines that i was added to the manifest to prevent from android out of memory exception ...
remove these two lines and every thing well be ok :
android:largeHeap="true"
android:hardwareAccelerated="false"
i hope this answer going to help you ...
do the height of relative layout ="wrap_content" instead of match parent , also of scrollview.

GridView goes messy

When I scroll past an item and come back to it, it changes it's position until I click on it, then it will correctly align itself. How can I solve this. Sorry I am still at the start of the project so my code is a bit messy.
This is my code:
package com.example.r_corp.androidslauncher;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
PackageManager packageManager;
Intent mainIntent = null;
static ArrayList<app> appList;
static GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show_all_apps_layout);
gridView = (GridView)findViewById(R.id.GridView);
gridView.setNumColumns(4);
packageManager = getPackageManager();
mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
appList = getApps();
show();
}
public ArrayList<app> getApps(){
List<ResolveInfo>apps = packageManager.queryIntentActivities(mainIntent, 0);
ArrayList<app> Apps = new ArrayList();
for(ResolveInfo ri : apps){
app App = new app();
App.icon = ri.loadIcon(packageManager);
App.Name = ri.loadLabel(packageManager).toString();
Apps.add(App);
}
return Apps;
}
public void show(){
ArrayAdapter<app> adapter = new ArrayAdapter<app>(this, R.layout.item,
appList) {
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.item,null);
}
ImageView appIcon = (ImageView) convertView
.findViewById(R.id.imageView);
appList.get(position).icon.setBounds(10,10,10,10);
appIcon.setImageDrawable(appList.get(position).icon);
appIcon.setLayoutParams(new RelativeLayout.LayoutParams(85, 85));
appIcon.setScaleType(ImageView.ScaleType.CENTER_CROP);
appIcon.setPadding(8, 8, 8, 8);
TextView appName = (TextView) convertView
.findViewById(R.id.textView);
appName.setText(appList.get(position).Name);
return convertView;
}
};
gridView.setFocusable(true);
gridView.setAdapter(adapter);
}
}
class app{
Drawable icon;
String Name;
}
show_all_apps_layout:
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:stretchMode="columnWidth"
android:focusableInTouchMode="true"
android:horizontalSpacing="5dp"
android:verticalSpacing="5dp"
android:id="#+id/GridView"/>
item:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
app:srcCompat="#mipmap/ic_launcher" />
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/imageView"
android:layout_centerHorizontal="true"
android:text="TextView" />
</RelativeLayout>
Thanks in advance for your helpfulness.

Loading Large Bitmaps Efficiently

There is a good link on how to load large Bitmaps efficiently, so that you don't get an OutOfMemory-Error.
Here ist the link: http://developer.android.com/training/displaying-bitmaps/load-bitmap.html
But my problem is, that I am a very newbie and I don't know how to understand the link. Could you please help me and modify my codes?
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" >
<ImageView
android:id="#+id/imageView2"
android:layout_width="250dp"
android:layout_height="250dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:onClick="Menue"
android:src="#drawable/ic_launcher" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="200dp"
android:layout_height="100"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:src="#drawable/pfeilrechts"
android:onClick="Picture2"/>
</RelativeLayout>
JAVA-Code:
package com.example.xxx;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class PictureOne extends Activity {
public ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.pictureone);
iv = (ImageView)findViewById(R.id.imageView2);}
{
ImageView.setImageBitmap(
decodeSampledBitmapFromResource(getResources(), R.id.imageView2, 100, 100));}
public void Picture2 (View view){
Intent i = new Intent(this, MainActivity.class);
startActivity(i);}}

Categories