Android Studio Can't pass TextView object between Fragment class and Thread - java

ERROR:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.TextView.setText(java.lang.CharSequence)' on a null
object reference
ON LINE:
olxLoadingFragment.pricesTextView.setText("some text");
I have one Fragment class that's called OLXLoadingFragment and it has one TextView nested in ScrollView. I basically want to update that TextView's text dynamically in my OLXThread, but can't pass that TextView object to the OLXThread itself. Here are code parts that could help you:
OLXLoadingFragment class:
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ScrollView;
import android.widget.TextView;
import java.io.Serializable;
public class OLXLoadingFragment extends Fragment {
public static View OLXLoadingFragmentView;
public static ScrollView scrollViewPrices;
public static TextView pricesTextView;
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
OLXLoadingFragmentView = inflater.inflate(R.layout.fragment_olx_loading, container, false);
scrollViewPrices = OLXLoadingFragmentView.findViewById(R.id.olx_scroller);
pricesTextView = OLXLoadingFragmentView.findViewById(R.id.olx_prices_text);
return inflater.inflate(R.layout.fragment_olx_loading, container, false);
}
}
OLXThread class:
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.widget.ScrollView;
import android.widget.TextView;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.w3c.dom.Text;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import static android.app.PendingIntent.getActivity;
public class OLXThread extends Thread {
public static double fullSum = 0.0d;
public static ArrayList<String> pricesPerPage = new ArrayList<String>();
public static ArrayList<String> pricesPerPage2 = new ArrayList<String>();
public static ArrayList<String> prices = new ArrayList<String>();
public static String toSearch;
public static TextView olxpricesView;
public static Context context;
public OLXThread(String toSearch) {
this.toSearch = toSearch;
}
public void run() {
//SET SOME TEXT TO TEXTVIEW HERE
OLXLoadingFragment olxLoadingFragment = new OLXLoadingFragment();
olxLoadingFragment.pricesTextView.setText("some text"); //<- DOESN'T WORK!
}
OLXLoadingFragment xml layout:
<?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">
<ImageView
android:id="#+id/imageView2"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#drawable/rectangle"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.82" />
<TextView
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:gravity="center"
android:text="#string/olx_loading_engl_text"
android:textColor="#color/limegreen"
android:textSize="30sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.82" />
<ImageView
android:id="#+id/imageView6"
android:layout_width="287dp"
android:layout_height="284dp"
android:src="#drawable/rectangle"
app:layout_constraintBottom_toBottomOf="#+id/olx_scroller"
app:layout_constraintEnd_toEndOf="#+id/olx_scroller"
app:layout_constraintStart_toStartOf="#+id/olx_scroller"
app:layout_constraintTop_toTopOf="#+id/olx_scroller" />
<ScrollView
android:id="#+id/olx_scroller"
android:layout_width="287dp"
android:layout_height="284dp"
android:layout_marginBottom="36dp"
android:fillViewport="true"
android:scrollbars="vertical"
app:layout_constraintBottom_toTopOf="#+id/imageView2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<TextView
android:id="#+id/olx_prices_text"
android:text="neki tekst"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1.0"
/>
</ScrollView>
</android.support.constraint.ConstraintLayout>
Please help!

At the time you call the method pricesTextView.setText(), the OnCreateView method of the Fragment wasn't called yet, so the pricesTextView was still null, as you only set it's value on the onCreateView method.
You should ensure that pricesTextView is not null before you call any method on this.
Note also that the only Thread that can touch views is the Ui thread, so even if your TextView is not null you cannot modify it's properties in other threads

Related

app crashes when getting a reference on android studio

I'm a newbie in programming and stuff.. I'm using the android-youtube-player package from Pierfrancesco Soffritti.. and when I try to Get a reference to YouTubePlayer and run the app it crashes..
`
package com.example.youtuuuuuuuuuuuuuuube;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.YouTubePlayer;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.AbstractYouTubePlayerListener;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.listeners.YouTubePlayerListener;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.options.IFramePlayerOptions;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.ui.DefaultPlayerUiController;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.ui.PlayerUiController;
import com.pierfrancescosoffritti.androidyoutubeplayer.core.ui.menu.YouTubePlayerMenu;
public class MainActivity extends AppCompatActivity {
private YouTubePlayer youTubePlayer;
private YouTubePlayerView youTubePlayerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void playvideo(View v){
youTubePlayer.loadVideo("S0Q4gqBUs7c", 1f);
}
}
`
my XML code
<LinearLayout
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"
android:orientation="vertical" >
<com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView
android:id="#+id/youtube_player_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:videoId="S0Q4gqBUs7c"
app:autoPlay="true"
/>
<Button
android:id="#+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="playvideo"
android:text="Button" />
I tried to get the reference using OnStart() method, added a button but all of that don't work :(

I received a message "cannot find symbol" but I already define in .xml file

Why am getting can not find the symbol? but I already defined "slider1" as a id. Therefore I clean the project and rebuild it again. But it does not work. How to solve that? I put the half of the code and an error was coming from
"sliderLayout = (SliderLayout)findViewById(R.id.slider1);"
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.daimajia.slider.library.Animations.DescriptionAnimation;
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.google.firebase.messaging.FirebaseMessaging;
import com.moraspirit.moraspiritapp.about.AboutActivity;
import com.moraspirit.moraspiritapp.article.ArticleActivity;
import com.moraspirit.moraspiritapp.homemenu.HomeMenuAdapter;
import com.moraspirit.moraspiritapp.homemenu.HomeMenuItem;
import com.moraspirit.moraspiritapp.homemenu.OnItemClickListener;
import com.moraspirit.moraspiritapp.points.RankingActivity;
import com.moraspirit.moraspiritapp.sports.MatchActivity;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class NewHomeActivity extends AppCompatActivity implements BaseSliderView.OnSliderClickListener, ViewPagerEx.OnPageChangeListener {
RecyclerView homeTiles;
List<HomeMenuItem> menuItems;
SliderLayout sliderLayout;
HashMap<String,String> Hash_file_maps ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_home);
Hash_file_maps = new HashMap<String, String>();
sliderLayout = (SliderLayout)findViewById(R.id.slider1);
Here is the activity_new_home.xml file.
<?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="#android:color/white"
tools:context=".NewHomeActivity">
<LinearLayout
android:id="#+id/textHome"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="8dp"
android:gravity="left"
android:orientation="vertical"
android:layout_alignParentTop="true"
android:background="#color/colorPrimary">
<ImageView
android:id="#+id/logo1"
android:layout_width="75dp"
android:layout_height="150dp"
android:layout_gravity="center"
android:elevation="6dp"
android:src="#drawable/logo"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
<com.daimajia.slider.library.SliderLayout
android:id="#+id/slider1"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_below="#+id/textHome"
android:orientation="horizontal"
/>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/home_tiles"
android:layout_width="401dp"
android:layout_height="382dp"
android:layout_below="#+id/slider1"
android:layout_marginTop="-1dp"
android:layout_marginRight="10dp"
android:scrollbars="vertical"
app:layout_constraintTop_toBottomOf="#+id/slider1">
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
Here is the pic about the error which am getting.
enter image description here

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.

Categories