How to display database data from an activity? - java

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;
}
}

Related

How to add firebase to a fragment in android studio

I am making an android ecommerce app and I downloaded an app template but in that template there is no firebase in the fragment and I want when the user clicks checkout button the products he selected should go to the firebase database but all videos I see they use activities .So please help me.
CartFragment.java
package com.example.shoppingcart.views;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;
import com.example.shoppingcart.R;
import com.example.shoppingcart.adapters.CartListAdapter;
import com.example.shoppingcart.cartholder;
import com.example.shoppingcart.databinding.FragmentCartBinding;
import com.example.shoppingcart.dataholder;
import com.example.shoppingcart.models.CartItem;
import com.example.shoppingcart.productholder;
import com.example.shoppingcart.viewmodels.ShopViewModel;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.firestore.FirebaseFirestore;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
public class CartFragment extends Fragment implements CartListAdapter.CartInterface {
private static final String TAG = "CartFragment";
private ImageView productImage;
private TextView productname;
private TextView productprice;
private TextView productcategory;
private Spinner productquantity;
UUID uuid = UUID.randomUUID();
String randomUUID = uuid.toString().trim();
ShopViewModel shopViewModel;
FragmentCartBinding fragmentCartBinding;
NavController navController;
Button button;
private void finishActivity() {
if (getActivity() != null) {
getActivity().finish();
}
}
public CartFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
fragmentCartBinding = FragmentCartBinding.inflate(inflater, container, false);
return fragmentCartBinding.getRoot();
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
navController = Navigation.findNavController(view);
final CartListAdapter cartListAdapter = new CartListAdapter(this);
fragmentCartBinding.cartRecyclerView.setAdapter(cartListAdapter);
fragmentCartBinding.cartRecyclerView.addItemDecoration(new DividerItemDecoration(requireContext(), DividerItemDecoration.VERTICAL));
shopViewModel = new ViewModelProvider(requireActivity()).get(ShopViewModel.class);
shopViewModel.getCart().observe(getViewLifecycleOwner(), new Observer<List<CartItem>>() {
#Override
public void onChanged(List<CartItem> cartItems) {
cartListAdapter.submitList(cartItems);
fragmentCartBinding.placeOrderButton.setEnabled(cartItems.size() > 0);
}
});
shopViewModel.getTotalPrice().observe(getViewLifecycleOwner(), new Observer<Double>() {
#Override
public void onChanged(Double aDouble) {
fragmentCartBinding.orderTotalTextView.setText("Total: PKR " + aDouble.toString());
}
});
button = (Button) getView().findViewById(R.id.placeOrderButton);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(CartFragment.this.getActivity(), CheckoutActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finishActivity();
}
});
}
#Override
public void deleteItem(CartItem cartItem) {
shopViewModel.removeItemFromCart(cartItem);
}
#Override
public void changeQuantity(CartItem cartItem, int quantity) {
shopViewModel.changeQuantity(cartItem, quantity);
}
}
fragment_cart.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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:orientation="vertical"
tools:context=".views.CartFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/cartRecyclerView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
tools:listitem="#layout/cart_row"
tools:itemCount="2"
/>
<Space
android:layout_width="match_parent"
android:layout_height="16dp" />
<TextView
android:id="#+id/orderTotalTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_margin="8dp"
android:text="Total: PKR 26"
android:textAppearance="#style/TextAppearance.MaterialComponents.Headline6" />
<Button
android:id="#+id/placeOrderButton"
style="#style/Widget.MaterialComponents.Button.UnelevatedButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_margin="8dp"
android:text="Proceed To Checkout"
android:textAppearance="#style/TextAppearance.MaterialComponents.Caption" />
</LinearLayout>
</ScrollView>
What kind of firebase database you have to use because both of the methods are similar...
activity and fragment method is same not any kind of change to the method ...
i will show you firestore method because i don't know which one you have to use
in fragment first initilize
FirebaseFirestore firebaseFirestore;
oncreateview initialize
firebaseFirestore = FirebaseFirestore.getInstance();
after you can perform all your crud operation and all thing but first two line is require
simple use bro...

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

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

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.

Viewpager set adapter on a null object reference [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I'm trying to create an app that introduces attractions of los angeles and restaurants of los angeles. The main page is a image of attraction and restaurant, when you click either one it will opens up more attraction or restaurant for people to read about the details. I am implementing listview, however my setadapter is not working. Please take a look at my code and help a newbie out! Thanks! The error code is as below and the codes of my program after that.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
MainActivity.java:
package com.example.android.tourguide;
import android.content.Context;
import android.content.Intent;
import android.media.Image;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void attractionList(View v) {
Intent intent = new Intent(this, attractionList.class);
startActivity(intent);
}
}
attractionList.java:
package com.example.android.tourguide;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
public class attractionList extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attraction_list);
ArrayList<Attraction> attractionArrayList = new ArrayList<>();
attractionArrayList.add(new Attraction(R.drawable.griffith, R.raw.attraction, "Griffith Observatory"));
AttractionAdapter attractionAdapter = new AttractionAdapter(this, attractionArrayList);
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(attractionAdapter);
}
}
AttractionAdapter.java:
package com.example.android.tourguide;
import android.content.Context;
import android.content.res.AssetManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class AttractionAdapter extends ArrayAdapter<Attraction> {
private ArrayList<Attraction> mArrayList = new ArrayList<>();
private Context mContext;
private String eachline;
public AttractionAdapter(Context context, ArrayList<Attraction> arrayList){
super(context,0, arrayList);
mArrayList = arrayList;
mContext = context;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listView = convertView;
if (listView == null) {
listView = LayoutInflater.from(mContext).inflate(R.layout.activity_attraction_list, parent, false);
}
Attraction attraction = mArrayList.get(position);
TextView textView = (TextView) listView.findViewById(R.id.attraction_name);
textView.setText(attraction.getmAttractionName());
ImageView attractionImage = (ImageView) listView.findViewById(R.id.attraction_image);
attractionImage.setImageResource(attraction.getImageResourceId());
try {
InputStream inputStream = getContext().getResources().openRawResource(attraction.getTextFile());
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
String eachline;
while ((eachline = br.readLine()) != null) {
TextView attractionDetails = (TextView) listView.findViewById(R.id.attraction_details);
attractionDetails.setText(eachline);
eachline = br.readLine();
// `the words in the file are separated by space`, so to get each words
// eachline = bufferedReader.readLine();
}br.close();
}
catch(IOException ioe){
// TODO Auto-generated catch block
ioe.printStackTrace();
}
TextView attractionName = (TextView) listView.findViewById(R.id.attraction_name);
attractionName.setText(attraction.getmAttractionName());
TextView attractionDetails = (TextView) listView.findViewById(R.id.attraction_details);
attractionDetails.setText(attraction.getTextFile());
return listView;
}
}
listView.xml:
<?xml version="1.0" encoding="utf-8"?>
<ListView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/list">
</ListView>
activity_attraction_list.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="wrap_content"
android:padding="16dp"
tools:context=".attractionList">
<ImageView
android:id="#+id/image"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_gravity="center_horizontal"
android:scaleType="centerCrop" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/image"
android:orientation="vertical">
<TextView
android:id="#+id/attraction_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textStyle="bold"
android:textColor="#android:color/black"
/>
<TextView
android:id="#+id/attraction_details"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="16dp"
android:paddingTop="16dp"
android:textAppearance="?android:textAppearanceMedium"
android:textColor="#android:color/black" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Read more"
android:textAllCaps="false" />
</LinearLayout>
</RelativeLayout>
You try to find listview that is not present in the activity_attraction_list.xml so your listview is null in your case.
Change this
public class attractionList extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attraction_list); //Change this line
To
setContentView(R.layout.listview);

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