Tablet UI not working - java

I am working on an app that presents a grid of popular movies to the users and when the user clicks on one of the items, it shows the details of the movie.
The app is working fine on phones but my tablet UI implementation is not working
I don't get any crashes as such it's just that when I tap on a movie, the Details don't show up on tablets.
Here's the link to the GitHub repo - https://github.com/Hackertronix/Project-Motion/tree/Stage_2?files=1
And here are the files which concern with the Tablet UI
activity_movies.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewpager_container">
</FrameLayout>
activity_movies.xml (layout-sw600dp )
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="#+id/viewpager_container">
<FrameLayout
android:id="#+id/details_container"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
>
</FrameLayout>
</FrameLayout>
</LinearLayout>
</FrameLayout>
MoviesActivity.java
package com.execube.genesis.views.activities;
import android.app.ActivityOptions;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.transition.Explode;
import android.view.View;
import com.execube.genesis.R;
import com.execube.genesis.model.Movie;
import com.execube.genesis.views.fragments.DetailsFragment;
import com.execube.genesis.views.fragments.PopularMoviesFragment;
import com.execube.genesis.views.fragments.TopRatedMoviesFragment;
import com.execube.genesis.views.fragments.ViewPagerFragment;
public class MoviesActivity extends AppCompatActivity implements PopularMoviesFragment.openDetailsListener,
TopRatedMoviesFragment.openDetailsListener{
boolean isTablet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movies);
if (findViewById(R.id.details_container) == null)//CHECKING FOR TABLET CONFIGURATION
{
isTablet=false;
}
else{
isTablet=true;
}
View view= findViewById(R.id.viewpager_container);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
getWindow().setStatusBarColor(Color.TRANSPARENT);
}
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setExitTransition(new Explode());
}
FragmentManager fragmentManager= getSupportFragmentManager();
Fragment fragment;
fragmentManager.findFragmentById(R.id.viewpager_container);
if(savedInstanceState==null)
{
fragment= new ViewPagerFragment();
fragmentManager.beginTransaction()
.add(R.id.viewpager_container,fragment)
.commit();
}
}
#Override
public void openDetails(Movie movie,ActivityOptions options) {
//options parameter is for the transition
if(isTablet)
{
//TODO Retain the transitions.
Bundle bundle=new Bundle();
bundle.putParcelable("PARCEL",movie);
DetailsFragment fragment= new DetailsFragment();
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction()
.replace(R.id.details_container,fragment)
.commit();
}
else{
Intent intent= new Intent(this,DetailsActivity.class);
intent.putExtra("PARCEL",movie);
startActivity(intent,options.toBundle());
}
}
}
DetailsActivity.java
package com.execube.genesis.views.activities;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.transition.Fade;
import android.transition.Slide;
import android.view.Gravity;
import android.view.View;
import com.execube.genesis.R;
import com.execube.genesis.views.fragments.DetailsFragment;
/**
* Created by Prateek Phoenix on 5/1/2016.
*/
public class DetailsActivity extends FragmentActivity {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
if (Build.VERSION.SDK_INT >= 21) {
getWindow().setStatusBarColor(getResources().getColor(R.color.details_status_bar));
Slide slide=new Slide(Gravity.BOTTOM);
slide.excludeTarget(android.R.id.statusBarBackground,true);
slide.excludeTarget(android.R.id.navigationBarBackground,true);
getWindow().setEnterTransition(slide);
postponeEnterTransition();
}
FragmentManager fragmentManager= getSupportFragmentManager();
Fragment fragment= fragmentManager.findFragmentById(R.id.details_container);
if(fragment==null)
{
Bundle arguments = new Bundle();
arguments.putParcelable("PARCEL",
getIntent().getParcelableExtra("PARCEL"));
fragment = new DetailsFragment();
fragment.setArguments(arguments);
fragmentManager.beginTransaction()
.add(R.id.details_container,fragment)
.commit();
}
}
}
DetailsFragment.java
package com.execube.genesis.views.fragments;
import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import com.execube.genesis.R;
import com.execube.genesis.model.Movie;
import com.execube.genesis.model.Review;
import com.execube.genesis.utils.API;
import com.execube.genesis.utils.OkHttpHandler;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import okhttp3.Call;
import okhttp3.Response;
/**
* Created by Prateek Phoenix on 4/30/2016.
*/
public class DetailsFragment extends Fragment {
private static final String TAG = "DETAILS";
private static final int DEFAULT_NUM_COLORS = 5;
private Movie mMovie;
public Intent intent;
private TextView mDetailTitle;
private TextView mReleaseDate;
private TextView mOverview;
private TextView mOverviewHeader;
private ImageView mBackdrop;
private Toolbar mToolbar;
private RatingBar mRatingBar;
private ArrayList<Review> mReviews;
public DetailsFragment() {
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_detail, container, false);
mBackdrop = (ImageView) view.findViewById(R.id.details_poster);
mToolbar = (Toolbar) view.findViewById(R.id.toolbar);
mDetailTitle = (TextView) view.findViewById(R.id.detail_title_text);
mReleaseDate = (TextView) view.findViewById(R.id.release_date);
mOverview = (TextView) view.findViewById(R.id.overview);
mOverviewHeader = (TextView) view.findViewById(R.id.overview_header);
mRatingBar = (RatingBar) view.findViewById(R.id.movie_rating);
Bundle bundle=getArguments();
mMovie=bundle.getParcelable("PARCEL");
String id = String.valueOf(mMovie.getId());
String reviewQueryUrl = API.MOVIES_BASE_URL + id + "/reviews" + API.API_KEY;
String trailerQueryUrl = API.MOVIES_BASE_URL+id+"/videos"+API.API_KEY;
mDetailTitle.setText(mMovie.getTitle());
mReleaseDate.setText(mMovie.getReleaseDate());
mRatingBar.setProgress((int) mMovie.getVoteAverage());
mOverview.setText(mMovie.getOverview());
if (Build.VERSION.SDK_INT != 21) {
Typeface fontBold = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Gotham-Rounded-Bold.ttf");
Typeface fontMedium = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Gotham-Rounded-Medium.ttf");
Typeface fontMediumLight = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Gotham-Rounded-Book_.ttf");
mDetailTitle.setTypeface(fontBold);
mReleaseDate.setTypeface(fontMedium);
mOverview.setTypeface(fontMediumLight);
mOverviewHeader.setTypeface(fontBold);
}
OkHttpHandler handler = new OkHttpHandler(reviewQueryUrl, mCallback);
handler.fetchData();
Picasso.with(getActivity()).load(API.IMAGE_URL + API.IMAGE_SIZE_500 + mMovie.getPosterPath())
.into(mBackdrop);
getActivity().startPostponedEnterTransition();
return view;
}
private okhttp3.Callback mCallback = new okhttp3.Callback() {
#Override
public void onFailure(Call call, IOException e) {
//TODO handle failure on UI thread
}
#Override
public void onResponse(Call call, Response response) throws IOException,IllegalStateException{
try {
String jsonResponse= response.body().string();
Log.v(TAG,jsonResponse );
JSONObject jsonObject = new JSONObject(jsonResponse);
int resultCount = jsonObject.getInt("total_results");
if (resultCount != 0) {
mReviews = parseReviews(jsonObject);
} else
mReviews = null;
} catch (JSONException e) {
}
catch (IllegalStateException e){}
}
};
private ArrayList<Review> parseReviews(JSONObject jsonObject) throws JSONException {
ArrayList<Review> Reviews = new ArrayList<>();
JSONArray reviewsJSONArray = jsonObject.getJSONArray("results");
for (int i = 0; i < reviewsJSONArray.length(); i++) {
Review review = new Review();
JSONObject reviewJson = reviewsJSONArray.getJSONObject(i);
review.setId(reviewJson.getInt("id"));
review.setAuthor(reviewJson.getString("author"));
review.setContent(reviewJson.getString("content"));
review.setTotalResults(reviewJson.getInt("total_results"));
Reviews.add(review);
}
return Reviews;
}
}

I think you should write same xml file for mobile and tablet in layout and
layout-sw600dp folder. System will pick by folder name. If you will open in phone it picks up layout from layout folder and if you will open in tablet it picks up
layout from layout-sw600dp folder.

Related

Why I can't define FindViewById() on Fragment with Volley Library

I am trying to define FindViewById() on Fragment with Volley Library. Also, I put FindViewById() on method OnResponse(), but I am getting an error. Do you have any solution? Here is my code.
package com.smktelkommlg.prakerinlistview;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SecondFragment extends Fragment {
private static final String BASE_URL = "Some Base URL";
private final String EndPoint = "Somr EndPoint";
List<Result> resultsLists;
ListView listView;
public SecondFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_second, container, false);
resultsLists = new ArrayList<>();
listView = rootView.findViewById(R.id.listView);
ProgressBar progressBar = rootView.findViewById(R.id.rolling);
loadResultsList();
// Instantiate the RequestQueue.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String idToDetail = String.valueOf(resultsLists.get(position).getId());
Intent detailIntent = new Intent(getActivity(),DetailActivity.class);
detailIntent.putExtra("idMoveIntent", idToDetail);
startActivity(detailIntent);
}
});
return rootView;
}
private void loadResultsList () {
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, BASE_URL+EndPoint+"?limit=1000&offset=0", new Response.Listener<String>() {
#Override
public void onResponse(String response) {
ProgressBar progressBar = findViewById(R.id.rolling);
Log.d("Json Response", response);
try {
JSONObject obj = new JSONObject(response);
JSONArray heroArray = obj.getJSONArray("results");
for (int i = 0; i < heroArray.length(); i++) {
JSONObject heroObject = heroArray.getJSONObject(i);
Result superHero = new Result(heroObject.getString("name"), heroObject.getInt("id"), heroObject.getJSONObject("device_role").getString("name"), heroObject.getJSONObject("status").getString("value"), heroObject.getJSONObject("device_type").getJSONObject("manufacturer").getString("slug"));
resultsLists.add(superHero);
}
ListViewAdapter adapter = new ListViewAdapter(resultsLists, getActivity().getApplicationContext());
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap header = new HashMap();
header.put("Content-Type", "application/json");
header.put("Authorization", "Token eaaa9e72d1a4f4c75aef7a7492e07785d853b6b4");
return header;
}
};
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
queue.add(stringRequest);
}
#Override
public void onViewCreated (#NonNull View view, #Nullable Bundle savedInstanceState){
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Results");
getContext();
}
}
I can't define this ProgressBar progressBar = findViewById(R.id.rolling);
Do I have to put ProgressBar progressBar = findViewById(R.id.rolling); in OnCreateView and use rootView? What should I do?
I meant to call progressBar before receive through the API.
(I'm sorry for my grammar. I hope you understand)
And here's my xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="#+id/rolling"
style="?android:attr/progressBarStyleLarge"
android:layout_width="match_parent"
android:indeterminate="true"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"/>
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
Use Global Variable
In your SecondFragment:
ProgressBar progressBar;
in OnCreateView:
progressBar = rootView.findViewById(R.id.rolling);
Remove ProgressBar progressBar = findViewById(R.id.rolling); from loadResultsList() method.

Problem with fragment communication(Attempt to invoke virtual method)

I have a tabbed activity with 2 fragments. I'm trying to transmit a string from the first fragment to the second fragment but I'm getting NULL POINTER EXCEPTION.
Here is the MainActivity.java:
package com.example.myapplication;
import android.os.Bundle;
import com.google.android.material.tabs.TabLayout;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;
import com.example.myapplication.ui.main.SectionsPagerAdapter;
public class MainActivity extends AppCompatActivity implements Frag1.Exchange {
private static final String TAG = "MainActivity";
private SectionsPagerAdapter sectionsPagerAdapter;
private ViewPager viewPager;
private TabLayout tabLayout;
private void setupViewPager(ViewPager viewPager){
SectionsPagerAdapter sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
sectionsPagerAdapter.addFragment(new Frag1(), "FirstTab");
sectionsPagerAdapter.addFragment(new Frag2(), "SecondTab");
viewPager.setAdapter(sectionsPagerAdapter);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.view_pager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
}
#Override
public void stringExchange(String s) {
Frag2 frag2 = (Frag2) getSupportFragmentManager().findFragmentByTag("SecondTab");
frag2.displayExchange(s);
}
}
Here is SectionsPagerAdapter.java
package com.example.myapplication.ui.main;
import android.content.Context;
import androidx.annotation.Nullable;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import com.example.myapplication.R;
import java.util.ArrayList;
import java.util.List;
/**
* A [FragmentPagerAdapter] that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> stringList = new ArrayList<>();
public void addFragment(Fragment fragment, String title){
fragmentList.add(fragment);
stringList.add(title);
}
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a (defined as a static inner class below).
return fragmentList.get(position);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return stringList.get(position);
}
#Override
public int getCount() {
// Show 2 total pages.
return fragmentList.size();
}
}
Here is Frag1.java:
package com.example.myapplication;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
public class Frag1 extends Fragment{
private static final String TAG = "FirstTab";
private Button transfer;
private Exchange ex;
public interface Exchange{
public void stringExchange(String s);
}
#Nullable
#Override
public View onCreateView(#NonNull final LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.tab1_fragment, container, false);
transfer = (Button) view.findViewById(R.id.button2);
ex = (Exchange) getActivity();
transfer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String s = "Test";
ex.stringExchange(s);
}
});
return view;
}
}
With its xlm tab1_fragment.xlm:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:id="#+id/tab1"
>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/transfer"
android:layout_centerInParent="true"/>
</RelativeLayout>
And finally here is the Frag2.java:
package com.example.myapplication;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import java.util.ArrayList;
public class Frag2 extends Fragment {
private static final String TAG = "SecondTab";
private ListView listView;
private ArrayList<String> arrayList = new ArrayList<>();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab2_fragment, container, false);
listView = (ListView) view.findViewById(R.id.list_view);
ArrayAdapter arrayAdapter = new ArrayAdapter(getContext(),android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(arrayAdapter);
return view;
}
public void displayExchange(String s){
arrayList.add(s);
}
}
I think the problem is in MainActivity when I call findFragmentByTag("SecondTab") because it's tag is not set to SecondTab but i don't know how to set it.
Any help will be apreciated!
Use ViewModel to share data between fragments. Refer: https://developer.android.com/topic/libraries/architecture/viewmodel.html#sharing

Can't Update Recyclerview adapter with new list,new list showing blank

I want to get new updated list in Favourite activity,but instead i'm getting no items in favourite list.List getting values from sharedpreference but not updating to recycler view.
DiseaseAdapter
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by admin on 12/4/2017.
*/
public class DiseaseAdapter extends RecyclerView.Adapter<DiseaseAdapter.DiseaseAdapterViewHolder> {
List <String> data;
Context ctx;
SharedPreference sharedPreference;
DiseaseAdapter(List <String> data, Context ctx){
this.data=data;
notifyDataSetChanged();
this.ctx=ctx;
sharedPreference = new SharedPreference();
}
#Override
public DiseaseAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater=LayoutInflater.from(parent.getContext());
View view= inflater.inflate(R.layout.activity_listview,parent,false);
return new DiseaseAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(DiseaseAdapterViewHolder holder, int position) {
final String title=data.get(position);
holder.textView1.setText(title);
if (checkFavoriteItem(title)) {
holder.imageButton.setImageResource(R.drawable.star_colour);
holder.imageButton.setTag("red");
} else {
holder.imageButton.setImageResource(R.drawable.ic_action_name);
holder.imageButton.setTag("grey");
}
}
#Override
public int getItemCount() {
return data.size();
}
class DiseaseAdapterViewHolder extends RecyclerView.ViewHolder {
TextView textView1;
ImageView imageButton;
public DiseaseAdapterViewHolder(View itemView) {
super(itemView);
textView1=(TextView) itemView.findViewById(R.id.textView);
imageButton=(ImageView)itemView.findViewById(R.id.imgbtn_favorite);
}
}
/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(String checkProduct) {
boolean check = false;
List<String> favorites = sharedPreference.getFavorites(ctx);
if (favorites != null) {
for (String product : favorites) {
if (product.equals(checkProduct)) {
check = true;
break;
}
}
}
return check;
}
}
MainActivity
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity{
RecyclerView simpleListView;
static Context ctx;
String diseaseList[];
SharedPreference sharedPreference;
DiseaseAdapter da;
List<String> newDiseaseList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ctx=this;
sharedPreference = new SharedPreference();
diseaseList= new String[]{"Abscess",
"Allergies",
"Amnesia",
"Anemia",
"Andropause",
"Angina",
"Weight Loss"};
Arrays.sort(diseaseList);
newDiseaseList = Arrays.asList(diseaseList);
simpleListView= (RecyclerView)findViewById(R.id.simpleListView);
LinearLayoutManager lm=new LinearLayoutManager(MainActivity.this);
simpleListView.setLayoutManager(lm);
/* DividerItemDecoration di=new DividerItemDecoration(MainActivity.this,lm.getOrientation());
simpleListView.addItemDecoration(di);*/
da=new DiseaseAdapter(newDiseaseList,ctx);
simpleListView.setAdapter(da);
simpleListView.setHasFixedSize(true);
simpleListView.addOnItemTouchListener(
new RecyclerItemClickListener(ctx, simpleListView ,new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
ImageView button = (ImageView) view.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx, newDiseaseList.get(position));
Toast.makeText(ctx,
"add to favourites",
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx, newDiseaseList.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
Toast.makeText(ctx,
"removed from favourites",
Toast.LENGTH_SHORT).show();
}
}
#Override public void onLongItemClick(View view, int position) {
}
})
);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_favorites:
Intent i=new Intent(this,Favourite.class);
this.startActivity(i);
return true;
}
return super.onOptionsItemSelected(item);
}
}
SharedPreference.java
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.google.gson.Gson;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SharedPreference {
public static final String PREFS_NAME = "PRODUCT_APP";
public static final String FAVORITES = "Product_Favorite";
public SharedPreference() {
super();
}
// This four methods are used for maintaining favorites.
public void saveFavorites(Context context, List<String> favorites) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public void addFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites == null)
favorites = new ArrayList<String>();
favorites.add(product);
saveFavorites(context, favorites);
}
public void removeFavorite(Context context, String product) {
List<String> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(product);
saveFavorites(context, favorites);
}
}
public ArrayList<String> getFavorites(Context context) {
SharedPreferences settings;
List<String> favorites ;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
String [] favoriteItems = (gson.fromJson(jsonFavorites,String [].class));
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<String>(favorites);
} else
return null;
return (ArrayList<String>) favorites;
}
}
Favourite.java
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
public class Favourite extends AppCompatActivity {
RecyclerView favoriteList;
SharedPreference sharedPreference;
List<String> favorites;
DiseaseAdapter diseaseAdapter;
Context ctx;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite);
ctx=this;
sharedPreference = new SharedPreference();
favorites = sharedPreference.getFavorites(ctx);
favoriteList = (RecyclerView)findViewById(R.id.favListView);
if (favorites == null) {
showAlert(getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
} else {
if (favorites.size() == 0) {
showAlert(
getResources().getString(R.string.no_favorites_items),
getResources().getString(R.string.no_favorites_msg));
}
if (favorites != null) {
diseaseAdapter = new DiseaseAdapter(favorites,ctx);
diseaseAdapter.notifyDataSetChanged();
favoriteList.setAdapter(diseaseAdapter);
favoriteList.invalidate();
favoriteList.addOnItemTouchListener(
new RecyclerItemClickListener(ctx, favoriteList ,new RecyclerItemClickListener.OnItemClickListener() {
#Override public void onItemClick(View view, int position) {
ImageView button = (ImageView) view
.findViewById(R.id.imgbtn_favorite);
String tag = button.getTag().toString();
if (tag.equalsIgnoreCase("grey")) {
sharedPreference.addFavorite(ctx,
favorites.get(position));
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.add_favr),
Toast.LENGTH_SHORT).show();
button.setTag("red");
button.setImageResource(R.drawable.star_colour);
} else {
sharedPreference.removeFavorite(ctx,
favorites.get(position));
button.setTag("grey");
button.setImageResource(R.drawable.ic_action_name);
/* diseaseAdapter.remove(favorites
.get(position));*/
diseaseAdapter.notifyItemRemoved(position);
Toast.makeText(
ctx,
ctx.getResources().getString(
R.string.remove_favr),
Toast.LENGTH_SHORT).show();
}
}
#Override public void onLongItemClick(View view, int position) {
}
})
);
}
}
}
public void showAlert(String title, String message) {
if (ctx != null) {
AlertDialog alertDialog = new AlertDialog.Builder(ctx)
.create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setCancelable(false);
// setting OK Button
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
// activity.finish();
getFragmentManager().popBackStackImmediate();
}
});
alertDialog.show();
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.admin.fav.MainActivity">
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/simpleListView"
>
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
activity_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="20dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:textColor="#434b3e"
android:text=""/>
<ImageView
android:id="#+id/imgbtn_favorite"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginRight="3dp"
android:background="#null"
/>
</RelativeLayout>
activity_favourite.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.admin.fav.Favourite">
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/favListView"
>
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
You are missing setLayoutManager() in Favourite.java.
Try calling NotifyDataSetChanged() instead of NotifyItemRemoved() or NotifyItemAdded(). These methods did not work for me either. You just won't get the animations of items being added and removed but you can add your own animations to do the trick!
You should use Room Database to store lists and handle them as it is much easier and makes a lot of sense. SharedPreferences is recommended for storing values such as integers and booleans, not whole lists.

Android programming - ListView with button

I am creating this layout where a list of text is displayed with a "delete" button besides each item. I am not able to get the layout right i guess. Can i get some help on this?
Here is the layout file for the list view:
<?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"
android:orientation="vertical" >
<ListView
android:id="#+id/locationList"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="#+id/delete"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FFFFFFFF"
android:text="Delete"
android:onClick="onClickDelete"/>
</ListView>
</RelativeLayout>
Here is the java code:
package com.android.ict.seneca.androidpocketguide;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class Websites extends Activity
implements AdapterView.OnItemClickListener{
private final String CLASS_NAME = "Websites";
DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy, HH:mm");
String date;
String location;
String name;
int counter;
List listName;
private SharedPreferences savedState;
private ListView listView;
private List<RowItem> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_websites);
listName= new ArrayList();
String app_name = "//sdcard//LocoLog.txt";
//int counter = 0, flag = 0;
String temp = "";
savedState = getSharedPreferences( "quantitySaved", MODE_PRIVATE );
rowItems = new ArrayList<RowItem>();
counter = savedState.getInt("counter", -1 );
if(counter!=-1)
{
for (int i = 1; i <= counter; i++)
{
String na;
String da;
String lo;
na = "name" + i;
da = "date" + i;
lo = "location" + i;
name = savedState.getString(na, "na" );
date = savedState.getString(da, "da" );
location = savedState.getString(lo, "lo" );
//Toast.makeText(this, "The data: "+name + " " + location + " " + date,Toast.LENGTH_LONG).show();
listName.add(new RowItem(name, location, date, counter));
}
}
else
{
Toast.makeText(this, "No locations saved yet",Toast.LENGTH_LONG).show();
}
listView = (ListView) findViewById(R.id.locationList);
listView.setAdapter( new CustomListAdapter(this, R.layout.list_item, listName ) );
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String cities = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(this, cities, Toast.LENGTH_LONG).show();
Intent myIntent = new Intent(view.getContext(), SingleListItem.class);
myIntent.putExtra("product", cities);
startActivityForResult(myIntent, 0);
}
public void onClickDelete(View view)
{
//String cities = String.valueOf(parent.getItemAtPosition(position));
Toast.makeText(this, "delete ", Toast.LENGTH_LONG).show();
//rowItems.remove(position);
}
public void onClickAdd(View view)
{
Toast.makeText(this, "add ", Toast.LENGTH_LONG).show();
}
public void onStart() {
super.onStart();
Log.d(CLASS_NAME, "onStart invoked!");
}
public void onPause() {
super.onPause();
Log.d(CLASS_NAME, "onPause invoked!!");
}
public void onResume() {
super.onResume();
Log.d(CLASS_NAME, "onResume invoked!!");
}
public void onStop() {
super.onStop();
Log.d(CLASS_NAME, "onStop invoked!!!");
}
public void onDestroy() {
super.onDestroy();
Log.d(CLASS_NAME, "onDestroy INVOKED!!!");
}
public void onRestart() {
super.onRestart();
Log.d(CLASS_NAME, "onRestart invoked!!");
}
}
You cannot add Button like this in listview.Your button should be in separate layout.
mainLayout.xml
<ListView
android:id="#+id/locationList"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
and your listview items layout i.e button in your case
buttons.xml
<Button
android:id="#+id/delete"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FFFFFFFF"
android:text="Delete"
android:onClick="onClickDelete"/>
and then in your Activity
listview.setAdapter(YourAdapter());
and then in your adapter's getView method()
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolderItem viewHolder;
if(convertView==null){
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(R.layout.buttons, parent, false);
viewHolder = new ViewHolderItem();
viewHolder.button = convertView.findViewById(R.id.button);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolderItem) convertView.getTag();
}
viewHolder.button.setOnClickListener(new View.onClickListener(){
public void onClick(){
//handle your on click.
}
});
return convertView;
}
Viewholder class
static class ViewHolderItem{
private Button button;
}
Read this for further information http://www.androidhive.info/2011/10/android-listview-tutorial

How to open context menu with button?

I trying to change the way i open the contextmenu in my application,
Now, to open the contextmenu i need to long click on the item (in the listview), and its work perfectly.
I want to change that and add a button next to each row on the listview and by click on the button, the Context menu will open.
I added a ImageButton to rawlayout.xml (I see the button next to each row now) but i cannot get the button from the activity.
When i trying access the button, The app crashed with the message: java.lang.NullPointerException: Attempt to read from field 'android.widget.ImageButton com.grade.ido.grades.ListDataAdaptar$LayoutHandler.BUTTON' on a null object reference.
The current contextmenu happening in DataListActivity.java
Update 26/02/2016: I update the relevent codes:
I want that i could get the ImageButton for each row in the listview in the DataListActivity.java. but I get the NullPointerException error.
As you can see, in sortList function at DataListActivity, i declare the imageButton (I also tried to declare at the top of the activity, but i got the same null error).
When i set the onclicklistner in ListDataAdapter, I can access to every row imageButton in the listview, and popup a differnt toast for each, But i cannot create a new contextmenu.
Thre is an option to call the contextmenu found in DataListActivity from the onclick at listDataAdapter?
This is my DataListActivity.java:
package com.grade.ido.grades;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import java.text.DecimalFormat;
import java.util.Vector;
public class DataListActivity extends ActionBarActivity {
ListView listView;
SQLiteDatabase sqLiteDatabase;
com.grade.ido.grades.CourseDbHelper courseDbHelper;
Cursor cursor;
com.grade.ido.grades.ListDataAdaptar listDataAdaptar;
Spinner sortSpinner;
Spinner yearSpinner;
Spinner semSpinner;
ArrayAdapter<String> sortAdapter;
ArrayAdapter<String> filterYearAdapter;
ArrayAdapter<String> filterSemAdapter;
private InterstitialAd mInterstitialAd;
private String tempGradeOld,tempGradeNew;
private String byYear,bySem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.grade.ido.grades.R.layout.update_course);
hideActionBar();
sortSpinner = (Spinner)findViewById(com.grade.ido.grades.R.id.sortSpinner);
yearSpinner = (Spinner)findViewById(R.id.yearSpinner);
semSpinner = (Spinner)findViewById(R.id.semSpinner);
String[] sortItems = new String[]{"Sort by","Course name","Year","Semester", "Grade", "Points"};
Vector<String> semItems = new Vector<>();
semItems.add("all");
sortAdapter = new ArrayAdapter<String>(this, R.layout.my_spinner_textview, sortItems);
filterYearAdapter = new ArrayAdapter<String>(this, R.layout.my_spinner_textview, new getData(getApplicationContext()).getYearItems());
filterSemAdapter = new ArrayAdapter<String>(this, R.layout.my_spinner_textview, semItems);
sortSpinner.setAdapter(sortAdapter);
semSpinner.setAdapter(filterSemAdapter);
yearSpinner.setAdapter(filterYearAdapter);
Bundle extras = getIntent().getExtras();
bySem="all";
byYear="all";
courseDbHelper = new com.grade.ido.grades.CourseDbHelper(getApplicationContext());
sqLiteDatabase = courseDbHelper.getReadableDatabase();
// System.out.println(extras.getString("SPINNER"));
int spinnerPosition = sortAdapter.getPosition(extras.getString("SORT_SPINNER"));
sortSpinner.setSelection(spinnerPosition);
System.out.println("extrras data " + extras);
if (extras==null){
Log.e("DATALISTACTIVITY", "extras null");
}
else {
Log.e("DATALISTACTIVITY", extras.toString());
}
TextView tAVR = (TextView) findViewById(R.id.avrAllCourse);
double tempAvr = new getData(getApplicationContext()).getTaverage();
int tempSum = new getData(getApplicationContext()).getSum();
if (tempSum==0){
tAVR.setText(Double.toString(0));
}
else {
tAVR.setText(new DecimalFormat("##.##").format(tempAvr));
}
cursor = courseDbHelper.getInformation(sqLiteDatabase, com.grade.ido.grades.UserCourse.NewCourseInfo._ID);
sortSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
cursor = courseDbHelper.getInformation(sqLiteDatabase, com.grade.ido.grades.UserCourse.NewCourseInfo._ID);
sortList(byYear,bySem);
} else if (position == 1) {
cursor = courseDbHelper.getInformation(sqLiteDatabase, com.grade.ido.grades.UserCourse.NewCourseInfo.COURSE);
sortList(byYear,bySem);
}
else if (position == 2) {
cursor = courseDbHelper.getInformation(sqLiteDatabase, com.grade.ido.grades.UserCourse.NewCourseInfo.YEAR);
sortList(byYear,bySem);
}
else if (position == 3) {
cursor = courseDbHelper.getInformation(sqLiteDatabase, com.grade.ido.grades.UserCourse.NewCourseInfo.SEMESTER);
sortList(byYear,bySem);
}
else if (position == 4) {
cursor = courseDbHelper.getInformation(sqLiteDatabase, com.grade.ido.grades.UserCourse.NewCourseInfo.GRADE);
sortList(byYear,bySem);
}
else if (position == 5) {
cursor = courseDbHelper.getInformation(sqLiteDatabase, com.grade.ido.grades.UserCourse.NewCourseInfo.POINTS);
sortList(byYear,bySem);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
listView = (ListView) findViewById(R.id.list_view);
View header = getLayoutInflater().inflate(R.layout.header, null);
listView.addHeaderView(header);
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("XXXXXXXXXXXXXXX");
AdRequest adRequest = new AdRequest.Builder()
.build();
mInterstitialAd.loadAd(adRequest);
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
}
AdView mAdView = (AdView) findViewById(R.id.adView);
mAdView.loadAd(adRequest);
}
public static int getLocationSpinner(String arr[], String a){
int loc=-1;
for (int i=0;i<arr.length;i++){
if (arr[i].equals(a)){
loc=i;
}
}
return loc;
}
public void sortList(String byYear,String bySem){
registerForContextMenu(listView);
listDataAdaptar = new ListDataAdaptar(getApplicationContext(),R.layout.row_layout);
listView.setAdapter(listDataAdaptar);
ImageButton button= (ImageButton) findViewById(R.id.settingsButton);
if (!cursor.moveToFirst()){
}
else {
do {
String year,semester,course,points,grade;
year = cursor.getString(0);
semester = cursor.getString(1);
course = cursor.getString(2);
points = cursor.getString(3);
grade = cursor.getString(4);
butt
addTheCourse(year, semester, course, points, grade,button);
}
while (cursor.moveToNext());
}
}
public void addTheCourse(String year,String semester,String course,String points,String grade,ImageButton but){
DataProvider dataProvider = new DataProvider(year, semester, course, points, grade,but);
listDataAdaptar.add(dataProvider);
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuInflater inflater = getMenuInflater();
if (((AdapterView.AdapterContextMenuInfo)menuInfo).position == 0) {
return;
}
inflater.inflate(R.menu.menu_data_list, menu);
menu.setHeaderTitle("Options");
}
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
final int mySelectedRowIndex = info.position-1;
com.grade.ido.grades.DataProvider raw2 = (com.grade.ido.grades.DataProvider) listDataAdaptar.getItem(mySelectedRowIndex);
switch (item.getItemId()) {
case R.id.update_item:
//case 1 code .....
return true;
case R.id.delete_item:
//case 2 code .....
return true;
case R.id.change_grade:
//case 3 code .....
return super.onOptionsItemSelected(item);
}
}
public void onBackPressed() {
startActivity(new Intent(this, MainActivity.class));
}
private void hideActionBar() {
//Hide the action bar only if it exists
if (getSupportActionBar() != null) {
getSupportActionBar().hide();
}
}
}
this is my ListDataAdapter.java
package com.grade.ido.grades;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.grade.ido.grades.*;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Ido on 08/08/2015.
*/
public class ListDataAdaptar extends ArrayAdapter{
List list = new ArrayList();
SQLiteDatabase sqLiteDatabase;
com.grade.ido.grades.CourseDbHelper courseDbHelper;
public ListDataAdaptar(Context context, int resource) {
super(context, resource);
}
static class LayoutHandler{
TextView YEAR,SEMESTER,COURSE,POINTS,GRADE;
ImageButton BUTTON;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutHandler layoutHandler;
if (row == null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(com.grade.ido.grades.R.layout.row_layout,parent,false);
layoutHandler = new LayoutHandler();
layoutHandler.YEAR = (TextView)row.findViewById(com.grade.ido.grades.R.id.textYear);
layoutHandler.SEMESTER = (TextView)row.findViewById(com.grade.ido.grades.R.id.textSemester);
layoutHandler.COURSE = (TextView)row.findViewById(com.grade.ido.grades.R.id.textCourse);
layoutHandler.POINTS = (TextView)row.findViewById(com.grade.ido.grades.R.id.textPoints);
layoutHandler.GRADE = (TextView)row.findViewById(com.grade.ido.grades.R.id.textGrade);
layoutHandler.BUTTON= (ImageButton) row.findViewById(R.id.settingsButton);
row.setTag(layoutHandler);
}
else{
layoutHandler = (LayoutHandler) row.getTag();
}
final com.grade.ido.grades.DataProvider dataProvider = (com.grade.ido.grades.DataProvider) this.getItem(position);
layoutHandler.YEAR.setText(dataProvider.getYear());
layoutHandler.SEMESTER.setText(dataProvider.getSemester());
layoutHandler.COURSE.setText(dataProvider.getCourse());
layoutHandler.POINTS.setText(dataProvider.getPoints());
layoutHandler.GRADE.setText(dataProvider.getGrade());
// layoutHandler.BUTTON.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// ContextMenu cm;
//
// Toast.makeText(getContext(), dataProvider.getCourse(),
// Toast.LENGTH_LONG).show();
}
});
return row;
}
}
row_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal">
<TextView
android:layout_width="40dp"
android:layout_height="wrap_content"
android:id="#+id/textGrade"
android:text="Grade"
android:gravity="center"
android:textColor="#000000"/>
<TextView
android:layout_width="30dp"
android:layout_height="wrap_content"
android:id="#+id/textPoints"
android:text="Points"
android:gravity="center"
android:textColor="#000000"/>
<TextView
android:layout_width="150dp"
android:layout_height="wrap_content"
android:id="#+id/textCourse"
android:text="Course"
android:gravity="center"
android:textColor="#000000"/>
<TextView
android:layout_width="60dp"
android:layout_height="wrap_content"
android:id="#+id/textSemester"
android:text="Semester"
android:gravity="center"
android:textColor="#000000"/>
<TextView
android:layout_width="30dp"
android:layout_height="wrap_content"
android:id="#+id/textYear"
android:text="Year"
android:gravity="center"
android:textColor="#000000"/>
<ImageButton
android:layout_width="32dp"
android:layout_height="32dp"
android:id="#+id/settingsButton"
android:src="#drawable/settings"
android:nestedScrollingEnabled="false" />
</LinearLayout>

Categories

Resources