ScrollView not scroll smoothly - java

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.

Related

how to display recyclerview in a fragment after fetching an api on the click of a button

I am trying to display some recipe data after you search the recipe in the search bar and click the search button inside the search fragment. I am using recycler view inside the search fragment to display the data below the search bar and the button.
Here is the code for the fragment_search.xml file
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Fragments.SearchFragment">
<!-- TODO: Update blank fragment layout -->
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ImageView
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerHorizontal="true"
android:layout_marginLeft="100dp"
android:layout_marginTop="-230dp"
android:src="#drawable/home_oval" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="FOODIES"
android:textSize="40dp"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
<SearchView
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:queryHint="Find your today's recipe"
android:iconifiedByDefault="false"
android:background="#drawable/searchoval"
android:id="#+id/searchbar"
/>
<Button
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="search"
android:background="#drawable/rounded_btn"
android:layout_below="#+id/searchbar"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:id="#+id/button1"/>
<ImageView
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerHorizontal="true"
android:src="#drawable/ic_man_searching_location_using_gps_2127154_0"
android:layout_below="#+id/button1"
android:id="#+id/searching_logo"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/searching_text"
android:text="Search for yummy delicacies today"
android:layout_centerHorizontal="true"
android:textAlignment="center"
android:fontFamily="#font/quicksand"
android:layout_below="#+id/searching_logo"
android:textSize="25dp"
android:textColor="#color/black"/>
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/button1"
android:id="#+id/recycler_view"
>
</androidx.recyclerview.widget.RecyclerView>
</RelativeLayout>
</FrameLayout>
Here is my SearchFragment.java file.
package com.example.recipeappandroid.Fragments;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.example.recipeappandroid.Adapter.RecipeAdapter;
import com.example.recipeappandroid.Model.Recipe;
import com.example.recipeappandroid.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class SearchFragment extends Fragment {
Button click;
//public static TextView fetchedText;
ImageView searching_logo;
TextView searching_text;
SearchView searchbar;
String query="";
RecyclerView recyclerView;
public static ArrayList<Recipe> recipeList;
public static RecipeAdapter recipeAdapter;
private RequestQueue mRequestQueue;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_search, container, false);
click = (Button) view.findViewById(R.id.button1);
//fetchedText = (TextView) view.findViewById(R.id.fetcheddata);
searchbar = (SearchView) view.findViewById(R.id.searchbar);
searching_logo = view.findViewById(R.id.searching_logo);
searching_text = view.findViewById(R.id.searching_text);
recyclerView = view.findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);
//recipeAdapter = new RecipeAdapter();
recyclerView.setAdapter(recipeAdapter);
recipeList = new ArrayList<>();
//getData();
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
query = searchbar.getQuery().toString();
String url = "http://localhost:5000/" + query;
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
JSONObject recipes = jsonObject.getJSONObject("recipe");
//Recipe recipe = new Recipe();
String recipe_img = recipes.getString("image");
String recipe_title = recipes.getString("label");
String recipe_data = recipes.getString("source");
recipeList.add(new Recipe(recipe_img,recipe_title,recipe_data));
}
recipeAdapter = new RecipeAdapter(getContext(), recipeList);
//recyclerView.setAdapter(recipeAdapter);
recipeAdapter.notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(SearchFragment.this,"Error Occured",Toast.LENGTH_SHORT).show();
error.printStackTrace();
}
});
mRequestQueue = Volley.newRequestQueue(getContext());
mRequestQueue.add(jsonArrayRequest);
/* Log.d("QUEEEERRRYYYY",query);
ApiCall process = new ApiCall(searching_logo,searching_text);
process.execute(query);*/
}
});
return view;
}
}
I am fething the api and setting the arraylists and adapter inside the onClick listener
but I keep getting the "E/RecyclerView: No adapter attached; skipping layout" Error in the logcat.
Here is the code for the adapter.
package com.example.recipeappandroid.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.recipeappandroid.Model.Recipe;
import com.example.recipeappandroid.R;
import com.example.recipeappandroid.Viewholder.recipeViewHolder;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class RecipeAdapter extends RecyclerView.Adapter<recipeViewHolder>{
private Context mContext;
private ArrayList<Recipe> mRecipe;
public RecipeAdapter(Context context,ArrayList<Recipe> recipe) {
mContext = context;
mRecipe = recipe;
}
public void setData(ArrayList<Recipe> mRecipe) {
this.mRecipe = mRecipe;
}
#NonNull
#Override
public recipeViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(mContext).inflate(R.layout.recycler_row, viewGroup, false);
return new recipeViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull recipeViewHolder viewHolder, int i) {
Recipe recipe = mRecipe.get(i);
Picasso.get().load(recipe.getImg()).into(viewHolder.image);
viewHolder.recipe_title.setText(recipe.getTitle());
viewHolder.recipe_data.setText(recipe.getData());
}
#Override
public int getItemCount() {
return mRecipe.size();
}
}
Here is my solution
//recipeAdapter = new RecipeAdapter();
recyclerView.setAdapter(recipeAdapter);
recipeList = new ArrayList<>();
//change code:
recipeList = new ArrayList<>();
recipeAdapter = new RecipeAdapter(getContext(), recipeList);
recyclerView.setAdapter(recipeAdapter);
//after get data in API:
//recipeAdapter = new RecipeAdapter(getContext(), recipeList);
//recyclerView.setAdapter(recipeAdapter);
recipeAdapter.notifyDataSetChanged();

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

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

Resources$NotFoundException: File res/drawable-anydpi-v21/ic_upsc.xml

i have created an app by using SVG and PNG Images it is perfectly working in android 5.1 and android 6.0 but other other version like android 4.4, 7.1 and 8.1 application crash and show me this error:
Fatal exception:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ejobbox.ejobbox/com.ejobbox.ejobbox.DrawerMenu}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class ImageView
FATAL EXCEPTION: main
Process: com.ejobbox.ejobbox, PID: 8648
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ejobbox.ejobbox/com.ejobbox.ejobbox.DrawerMenu}: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class ImageView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Caused by: android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class ImageView
Caused by: android.view.InflateException: Binary XML file line #0: Error inflating class ImageView
Caused by: android.content.res.Resources$NotFoundException: Drawable com.ejobbox.ejobbox:drawable/ic_upsc with resource ID #0x7f0700a2
Caused by: android.content.res.Resources$NotFoundException: File res/drawable-anydpi-v21/ic_upsc.xml from drawable resource ID #0x7f0700a2
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:287)
I am currently using android studio 3.0 version so please let me know how can i fix it. i have added
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
but the error is not fixed, so please help me to resolve this error.
activity_drawer_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawermenu"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ejobbox.ejobbox.DrawerMenu">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?attr/backgroundcolor"
android:orientation="vertical"
android:padding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clipToPadding="false"
android:gravity="center"
android:orientation="horizontal"
android:weightSum="4">
<android.support.v7.widget.CardView
android:id="#+id/card_add1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="3dp"
android:layout_weight="1"
android:background="?attr/cardbackground">
<LinearLayout
android:id="#+id/LayerImg1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="?attr/cardbackground"
android:gravity="center"
android:orientation="vertical"
android:padding="2dp">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp">
<ImageView
android:id="#+id/img1"
android:layout_width="60dp"
android:layout_height="60dp"
android:background="#drawable/border"
android:padding="5dp"
android:src="#drawable/ic_letestjob" />
<TextView
android:id="#+id/badgeCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/img1"
android:layout_alignTop="#+id/img1"
android:layout_marginRight="-2dip"
android:layout_marginTop="-2dip"
android:background="#drawable/item_count"
android:gravity="center"
android:textColor="#FFF"
android:textSize="10sp"
android:textStyle="bold"
android:text="10"
android:visibility="visible" />
</RelativeLayout>
<TextView
android:id="#+id/ltsjobs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/img1"
android:layout_marginTop="-10dp"
android:background="#drawable/txtborder"
android:gravity="center"
android:paddingBottom="1dp"
android:paddingLeft="3dp"
android:paddingRight="3dp"
android:paddingTop="1dp"
android:text="Latest Jobs"
android:textColor="?attr/icontextcolor"
android:textStyle="bold" />
</LinearLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/BankingIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="3dp"
android:layout_weight="1"
android:background="?attr/cardbackground">
<LinearLayout
android:id="#+id/LayerBanking"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="?attr/cardbackground"
android:gravity="center"
android:orientation="vertical"
android:padding="2dp">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp">
<ImageView
android:id="#+id/BankingLogo"
android:layout_width="60dp"
android:layout_height="60dp"
android:background="#drawable/border"
android:padding="5dp"
android:src="#drawable/ic_banking" />
<TextView
android:id="#+id/BankingBadge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/BankingLogo"
android:layout_alignTop="#+id/BankingLogo"
android:layout_marginRight="-2dip"
android:layout_marginTop="-2dip"
android:background="#drawable/item_count"
android:gravity="center"
android:textColor="#FFF"
android:textSize="11sp"
android:textStyle="bold"
android:visibility="gone" />
</RelativeLayout>
<TextView
android:id="#+id/BankingTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/BankingLogo"
android:layout_marginTop="-10dp"
android:background="#drawable/txtborder"
android:gravity="center"
android:paddingBottom="1dp"
android:paddingLeft="3dp"
android:paddingRight="3dp"
android:paddingTop="1dp"
android:text="Banking"
android:textColor="?attr/icontextcolor"
android:textStyle="bold" />
</LinearLayout>
</android.support.v7.widget.CardView>
<android.support.v7.widget.CardView
android:id="#+id/PoliceIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="3dp"
android:layout_weight="1"
android:background="?attr/cardbackground">
<LinearLayout
android:id="#+id/LayerPolice"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="?attr/cardbackground"
android:gravity="center"
android:orientation="vertical"
android:padding="2dp">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp">
<ImageView
android:id="#+id/PoliceLogo"
android:layout_width="60dp"
android:layout_height="60dp"
android:background="#drawable/border"
android:padding="5dp"
android:src="#drawable/ic_police" />
<TextView
android:id="#+id/PoliceBadge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/PoliceLogo"
android:layout_alignTop="#+id/PoliceLogo"
android:layout_marginRight="-2dip"
android:layout_marginTop="-2dip"
android:background="#drawable/item_count"
android:gravity="center"
android:textColor="#FFF"
android:textSize="11sp"
android:textStyle="bold"
android:visibility="gone" />
</RelativeLayout>
<TextView
android:id="#+id/PoliceTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/PoliceLogo"
android:layout_marginTop="-10dp"
android:background="#drawable/txtborder"
android:gravity="center"
android:paddingBottom="1dp"
android:paddingLeft="3dp"
android:paddingRight="3dp"
android:paddingTop="1dp"
android:text="Police"
android:textColor="?attr/icontextcolor"
android:textStyle="bold" />
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigationMenuView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="?attr/backgroundcolor"
app:headerLayout="#layout/header"
app:itemIconTint="?attr/tintcolor"
app:itemTextColor="?attr/textcolor"
app:menu="#menu/drawermenu">
</android.support.design.widget.NavigationView>
</android.support.v4.widget.DrawerLayout>
DrawerMenu.java
package com.ejobbox.ejobbox;
import android.app.Activity;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.renderscript.Sampler;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatDelegate;
import android.support.v7.widget.CardView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.ShareActionProvider;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.ejobbox.ejobbox.Helper.LocalHelper;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.MobileAds;
import com.google.firebase.analytics.FirebaseAnalytics;
import com.google.firebase.crash.FirebaseCrash;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;
import cc.cloudist.acplibrary.ACProgressConstant;
import cc.cloudist.acplibrary.ACProgressPie;
import in.galaxyofandroid.spinerdialog.OnSpinerItemClick;
import in.galaxyofandroid.spinerdialog.SpinnerDialog;
import io.paperdb.Paper;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class DrawerMenu extends AppCompatActivity implements View.OnClickListener {
private ArrayList<Model> list;
private String baseURL = "http://ejobbox.com/";
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mToggle;
private NavigationView navMenuView;
SharedPreferences sharedPreferences;
private FirebaseAnalytics mFirebaseAnalytics;
Context context;
boolean doubleBackToExitPressed = false;
SharedPref sharedpref;
SharedPref Languagepref;
private float cVersion;
private String Applink;
private boolean is_first=true;
private String cVer;
private Menu menu;
ArrayList<String> items = new ArrayList<>();
ArrayList<String> Qualiitems = new ArrayList<>();
SpinnerDialog spinnerDialog;
SpinnerDialog spinnerDialogQuali;
ImageView imageView;
int GetMenuid;
public static final String PREFS_NAME = "Datakey";
public static final String PREFS_NAME2 = "Updatekey";
private CardView BtnAdd1, BtnAdd2, BtnAdd3, BtnAdd4, BtnAdd5, BtnAdd6, BtnAdd7, BtnAdd8, BtnAdd9, BtnAdd10, BtnAdd11, BtnAdd12, BtnAdd13, BtnAdd14, BtnAdd15, BtnAdd16, BtnAdd17, BtnAdd18;
int getBadgedataInt;
int getOLDVALUEInt;
int jobResponseValue;
int ResultUpd = 0;
int BankingValue;
int getBankingOLD;
int BankingResult = 0;
int ResultValue, AdmitCardValue, PoliceValue, RailwayValue, SscValue, UpscValue, DefenceValue, ITComputerValue, EngereeningValue, MedicalValue, SPSCValue, ITIValue, TeacherValue, InterviewValue, AdmitionValue, OtherjobValue;
int getResultOLD, getAdmitCardOLD, getPoliceOLD, getRailwayOLD, getSscOLD, getUpscOLD, getITComputerOLD, getDefenceOLD, getEngereeningOLD, getMedicalOLD, getSPSCOLD, getITIOLD, getTeacherOLD, getInterviewOLD, getAdmitionOLD, getOtherjobOLD;
int ResultResult = 0, AdmitResult = 0, PoliceResult = 0, RailwayResult = 0, SscResult = 0, UpscResult = 0, ITComputerResult = 0, DefenceResult = 0, EngereeningResult = 0, MedicalResult = 0, ITIResult = 0, SPSCResult = 0, TeacherResult = 0, InterviewResult = 0, AdmitionResult = 0, OtherjobResult = 0;
TextView ltsJobs, TextLang, BankingTxt, PoliceTxt, RailwayTxt, Ssctxt, UpscTxt, ITItxt, DefenceTxt, ITTxt, Teachertxt, InterviewTxt, AdmitionTxt, EngerTxt, MedicalTxt, spscTxt, OtherTxt, ResultTxt, AdmitTxt,StateTxt,QualiTxt;
private AdView mAdView;
#Override
protected void attachBaseContext(Context newBase) {
super.attachBaseContext(LocalHelper.onAttach(newBase, "en"));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
sharedpref = new SharedPref(this);
if (sharedpref.loadNightModeState() == true) {
setTheme(R.style.darktheme);
} else setTheme(R.style.AppTheme);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer_menu);
android.widget.Toolbar toolbar=(android.widget.Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("EJOBBOX");
AppCompatDelegate.setCompatVectorFromResourcesEnabled(true);
checkInternetConenction();
//TODO:Google ADS sense
MobileAds.initialize(this, "ca-app-pub-3940256099942544~3347511713");
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
// todo: Obtain the FirebaseAnalytics instance.
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
mFirebaseAnalytics.setAnalyticsCollectionEnabled(true);
mFirebaseAnalytics.setMinimumSessionDuration(20000);
final TextView badge = (TextView) findViewById(R.id.badgeCount);
final TextView Banking = (TextView) findViewById(R.id.BankingBadge);
final TextView Railway = (TextView) findViewById(R.id.RailwayBadge);
final TextView Police = (TextView) findViewById(R.id.PoliceBadge);
final TextView SSC = (TextView) findViewById(R.id.SscBadge);
final TextView UPSC = (TextView) findViewById(R.id.UpscBadge);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawermenu);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
navMenuView = (NavigationView) findViewById(R.id.navigationMenuView);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
BtnAdd1 = (CardView) findViewById(R.id.card_add1);
BtnAdd2 = (CardView) findViewById(R.id.BankingIcon);
BtnAdd3 = (CardView) findViewById(R.id.PoliceIcon);
BtnAdd4 = (CardView) findViewById(R.id.RailwayIcon);
BtnAdd5 = (CardView) findViewById(R.id.SscIcon);
BtnAdd6 = (CardView) findViewById(R.id.UpscIcon);
//add Click Listner
BtnAdd1.setOnClickListener(this);
BtnAdd2.setOnClickListener(this);
BtnAdd3.setOnClickListener(this);
BtnAdd4.setOnClickListener(this);
BtnAdd5.setOnClickListener(this);
BtnAdd6.setOnClickListener(this);
sharedPreferences = getSharedPreferences(PREFS_NAME, 0);
final SharedPreferences.Editor editors = sharedPreferences.edit();
navMenuView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Intent MenuIntent;
switch (item.getItemId()) {
case R.id.Alljobs:
MenuIntent = new Intent(DrawerMenu.this, AllJobsPage.class);
MenuIntent.putExtra("UpdResult", String.valueOf(jobResponseValue));
MenuIntent.putExtra("jobID", "190");
MenuIntent.putExtra("JOBSSTATE", R.string.All_jobs);
startActivity(MenuIntent);
break;
case R.id.countdown:
MenuIntent = new Intent(DrawerMenu.this, ExamCountdown.class);
startActivity(MenuIntent);
break;
case R.id.jobsummary:
MenuIntent = new Intent(DrawerMenu.this, JobSummary.class);
startActivity(MenuIntent);
break;
default:
break;
}
return false;
}
});
//TODO: Check Internet Connection [End]
private void initItems() {
for (int i = 0; i < 1; i++) {
items.add(this.getResources().getString(R.string.All_india));
items.add(this.getResources().getString(R.string.AndraPradesh));
items.add(this.getResources().getString(R.string.ArunachalPrades));
items.add(this.getResources().getString(R.string.Assam));
items.add(this.getResources().getString(R.string.Bihar));
}
}
private void eduQulification() {
for (int i = 0; i < 1; i++) {
Qualiitems.add(this.getResources().getString(R.string.ssc));
Qualiitems.add(this.getResources().getString(R.string.hsc));
Qualiitems.add(this.getResources().getString(R.string.Diploma));
Qualiitems.add(this.getResources().getString(R.string.ITI));
Qualiitems.add(this.getResources().getString(R.string.Graduate));
}
}
// Searching With Spinner[END]
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
GetMenuid= v.getId();
Intent i;
// i = new Intent(this, police.class);
switch (v.getId()) {
case R.id.card_add1:
i = new Intent(this, AllJobsPage.class);
i.putExtra("UpdResult", String.valueOf(jobResponseValue));
i.putExtra("jobID", "190");
i.putExtra("JOBSSTATE", R.string.All_jobs);
startActivity(i);
break;
case R.id.BankingIcon:
i = new Intent(this, police.class);
i.putExtra("BankingUPD",String.valueOf(BankingValue));
i.putExtra("jobID","197");
i.putExtra("JOBSSTATE",this.getResources().getString(R.string.Banking_Jobs));
startActivity(i);
break;
case R.id.PoliceIcon:
i = new Intent(this, police.class);
i.putExtra("PoliceUPD",String.valueOf(PoliceValue));
i.putExtra("jobID","198");
i.putExtra("JOBSSTATE",this.getResources().getString(R.string.Police_Jobs));
startActivity(i);
break;
default:
break;
}
}
private void setSupportActionBar(android.widget.Toolbar toolbar) {
if(getSupportActionBar()!=null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
}
//TODO: Actionbar Share Button
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.memu_items,menu);
MenuItem menushare=menu.findItem(R.id.sharMenu);
ShareActionProvider mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menushare);
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,DrawerMenu.this.getResources().getString(R.string.shareTitle));
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, DrawerMenu.this.getResources().getString(R.string.shareContent)+"\n"+DrawerMenu.this.getResources().getString(R.string.applink));
mShareActionProvider.setShareIntent(sharingIntent);
return true;
}
}
move all drawables located in the folder "/res/drawable-anydpi-v21" into the normal drawable folder.
See also error message line:
Caused by: android.content.res.Resources$NotFoundException: File res/drawable-anydpi-v21/ic_upsc.xml from drawable resource ID #0x7f0700a2
To support the different resolutions of image files, it is best to use the following folders:
drawable-ldpi
drawable-mdpi
drawable-hdpi
drawable-xhdpi
drawable-xxhdpi
drawable-xxxhdpi
Hope that could solve your problem

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