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
Related
So I have to convert an activity into a fragment. I followed some basic principles however the app still crashes.
The converted activity code:
package com.example.computerscienceiawithtablayout;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import java.io.File;
import java.util.*;
public class FragmentHome extends Fragment implements AddBookDialogue.AddBookDialogueListener{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
return inflater.inflate(R.layout.fragment_home, container, false);
}
#Override
public void onStart() {
super.onStart();
}
public void onBigButtonClick(View w) {
AddBookDialogue addBookDialogue = new AddBookDialogue();
addBookDialogue.show(getChildFragmentManager(), "add book dialogue");
}
#Override
public void getTexts(String bookAuthor, String bookTitle, String bookBarcode, String bookCourse, String selectedBookshelf) {
if(bookAuthor.isEmpty() || bookTitle.isEmpty() || bookBarcode.isEmpty() || bookCourse.isEmpty()){
Toast.makeText(getActivity(), "You didn't enter all necessary data", Toast.LENGTH_LONG).show();
}else{
if(bookBarcode.length()!=8){
Toast.makeText(getActivity(), "Barcodes should be eight digits long", Toast.LENGTH_LONG).show();
}else{ if(selectedBookshelf.equals("Withdrawn")){
Book a = new Book(bookAuthor, bookTitle, bookBarcode, bookCourse, selectedBookshelf);
Toast.makeText(getActivity(), a.toString(), Toast.LENGTH_LONG).show();
}else{
Book a = new Book(bookAuthor, bookTitle, bookBarcode, bookCourse, selectedBookshelf);
Toast.makeText(getActivity(), a.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
}
The fragment call upon an addBookDialogue, which is a dialoguefragment, code here:
package com.example.computerscienceiawithtablayout;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatDialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
public class AddBookDialogue extends AppCompatDialogFragment{
private EditText editTextBookAuthor;
private EditText editTextBookTitle;
private EditText editTextBookCourse;
private EditText editTextBookBarcode;
private Spinner spinnerBookshelf;
private AddBookDialogueListener listener;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getParentFragment().getActivity());
LayoutInflater inflater = getParentFragment().getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.dialogue_addbook, null);
builder.setView(view)
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String bookAuthor = editTextBookAuthor.getText().toString();
String bookTitle = editTextBookTitle.getText().toString();
String bookBarcode = editTextBookBarcode.getText().toString();
String bookCourse = editTextBookCourse.getText().toString();
String seletecBookshelf = spinnerBookshelf.getSelectedItem().toString();
listener.getTexts( bookAuthor, bookTitle, bookBarcode, bookCourse, seletecBookshelf);
}
});
editTextBookAuthor = view.findViewById(R.id.author);
editTextBookTitle= view.findViewById(R.id.bookTitle);
editTextBookBarcode= view.findViewById(R.id.bookBarcode);
editTextBookCourse= view.findViewById(R.id.bookBarcode);
spinnerBookshelf= view.findViewById(R.id.spinnerBookshelf);
ArrayAdapter<CharSequence> spinnerAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.addBookBookshelfsAvailable, android.R.layout.simple_spinner_item);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerBookshelf.setAdapter(spinnerAdapter);
return builder.create();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
listener = (AddBookDialogueListener) context;
} catch(ClassCastException e){
throw new ClassCastException(context.toString() + "no listener");
}
}
public interface AddBookDialogueListener{
void getTexts(String bookAuthor, String bookTitle, String bookBarcode, String bookCourse, String selectedBookshelf);
}
}
I am huge newbie and basing some of this code on intuition. The major flaws that I can think of are calling the addBookDialogue with .show(getChildFragmentManager) and in AddBookDialogue file setting the builder to getParentFragment.getActivity This probably isn't the correct approach, but I am having difficulties understanding the interactions between fragments. The book object is a simple java class with a constructor and a few setters/getters
So yeah, idk where to problem is, all help appreciated :)
For more reference here is the xml file for the main activity
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FragmentHome">
<fragment
android:id="#+id/fragmentHome"
android:name="com.example.computerscienceiawithtablayout.FragmentHome"
android:layout_height="match_parent"
android:layout_width="match_parent"/>
</android.support.constraint.ConstraintLayout>
and here is the xml for the fragment
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FragmentHome">
<Button
android:text="#string/Add"
android:textStyle="bold"
android:textColor="#ffffff"
android:background="#drawable/button_states"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:onClick="onBigButtonClick"
app:layout_constraintTop_toTopOf="parent"
android:layout_marginTop="480dp" app:layout_constraintStart_toStartOf="parent"
android:layout_marginStart="164dp" style="#style/Widget.AppCompat.Button"/>
</android.support.constraint.ConstraintLayout>
I have a problem when i use setOnItemClickListener to get the id of clicked item in GridView return null. I try to do that because I want when a user click an item I retrieve data from db then represent it in another fragment so there is a solution to get id or there are another way to deal with that. thanks a lot.
I use an Adapter:
The fragment.java
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import com.example.mohamed.osarelkheir.Adapters.Section_Adapter;
import com.example.mohamed.osarelkheir.First_Launch;
import com.example.mohamed.osarelkheir.Models.Section_Model;
import com.example.mohamed.osarelkheir.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.DocumentChange;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.EventListener;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreException;
import com.google.firebase.firestore.Query;
import com.google.firebase.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Sections_Fragment extends Fragment {
private GridView Dep_grid_View; //object from GridView (list) -Session Fragment
private List<Section_Model> Dep_list; //Data Model Object
private Section_Adapter section_adapter; //Adapter Object
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth firebaseAuth;
private String Dep_id;
private String item;
private DocumentSnapshot lastVisible; //to print the last ....
//Empty Contractor
public Sections_Fragment() {
}
private FragmentManager fragmentManager;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.section_fragment, container, false);
Dep_grid_View = view.findViewById(R.id.gridSection);
Dep_list = new ArrayList<>();
firebaseAuth = FirebaseAuth.getInstance();
firebaseFirestore = FirebaseFirestore.getInstance();
// myList = Arrays.asList(section_models); //he create its own array list to view it as a templet data cooooool
section_adapter = new Section_Adapter(getContext(), Dep_list);
Dep_grid_View.setAdapter(section_adapter);
//First Query
Query firstQuery = firebaseFirestore.collection("Department");
firstQuery.addSnapshotListener(getActivity(), new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#javax.annotation.Nullable QuerySnapshot snapshots, #javax.annotation.Nullable FirebaseFirestoreException e) {
// Toast.makeText(getActivity(), "No", Toast.LENGTH_SHORT).show();
for (DocumentChange doc : snapshots.getDocumentChanges()) {
// Toast.makeText(getActivity(), "NoO", Toast.LENGTH_SHORT).show();
if (doc.getType() == DocumentChange.Type.ADDED) {
// Toast.makeText(getActivity(), "No00", Toast.LENGTH_SHORT).show();
Dep_id = doc.getDocument().getId();
Toast.makeText(getActivity(), "Id" + Dep_id, Toast.LENGTH_SHORT).show();
// <<<<<<<<<<<<<GET DATA from DB >>>>>>>>>>>>>>>>>>
Section_Model section_model = doc.getDocument().toObject(Section_Model.class).withId(Dep_id);
//<<<<<<<<<<<<<<<then Put it in object of BlogList >>>>>>>>>>>>>>
Dep_list.add(section_model);
section_adapter.notifyDataSetChanged();
}
}
}
});
Dep_grid_View.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//it's return null
item = Dep_grid_View.getItemAtPosition(i).toString();
printadminview();
}
});
return view;
}
void printadminview() {
Intent intent = new Intent(getContext(), First_Launch.class);
intent.putExtra("value", 3);
intent.putExtra("Dep_ID", item );
// Toast.makeText(getActivity(), "pos " + pos, Toast.LENGTH_SHORT).show();
getContext().startActivity(intent);
}
}
The .xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<SearchView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:background="#drawable/item_background_manage"
android:layout_marginTop="5dp"
android:layout_marginEnd="5dp"
android:layout_marginStart="5dp"
android:layout_weight="1"
android:queryHint="search"/>
</LinearLayout>
<GridView
android:id="#+id/gridSection"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:numColumns="auto_fit"
android:verticalSpacing="5dp"
android:horizontalSpacing="3dp"
android:layout_margin="8dp" />
</LinearLayout>
Adapter class
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.support.annotation.NonNull;
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 com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.mohamed.osarelkheir.First_Launch;
import com.example.mohamed.osarelkheir.Models.Section_Model;
import com.example.mohamed.osarelkheir.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.List;
public class Section_Adapter extends ArrayAdapter<Section_Model> { //1
private Context mContext;
private List<Section_Model> data;
public Section_Adapter(Context mContext,List<Section_Model> data) {//2
super(mContext,R.layout.item_section,data);
this.mContext = mContext;
this.data = data;
}
#Override
public View getView(int position, View convertView, #NonNull ViewGroup parent) {
View row = convertView;
ViewHolder holder;
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(R.layout.item_section, parent, false);
holder = new ViewHolder();
holder.txtSectionName = row.findViewById(R.id.sectionName);
holder.imageView = row.findViewById(R.id.imageSection);
holder.imageIc = row.findViewById(R.id.ic_sec);
row.setTag(holder);
row.setTag(new Integer(position));
} else {
holder = (ViewHolder) row.getTag();
}
setView(holder, position);
Section_Model model = getItem(position);
String id = model.getId();
Intent intent=new Intent(mContext, First_Launch.class);
intent.putExtra("value",1);
intent.putExtra("DepartmentId", id);
mContext.startActivity(intent);
return row;
}
private void setView(ViewHolder holder, int position) {
Section_Model section_model = data.get(position);
holder.txtSectionName.setText(section_model.getSection_name());
String downlaodUriImage = section_model.getSection_image();
String DownloadUriLogo = section_model.getSection_icon();
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.logo);
Glide.with(mContext).applyDefaultRequestOptions(requestOptions).load(downlaodUriImage).into(holder.imageView);
Glide.with(mContext).load(DownloadUriLogo).apply(requestOptions.override(40,40)).into(holder.imageIc);
}
static class ViewHolder {
TextView txtSectionName;
ImageView imageView;
ImageView imageIc;
}
}
To only get the id, you just need to use the following code lines.
firstQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
String documentId = document.getId();
Log.d(TAG, documentId);
}
}
}
});
There is no need to use addSnapshotListener unless you need to get data in real-time. The output will be:
CIcg...
E30F...
rXY9...
If you need to get the corresponding id of item that was clicked, simply use getItem(position);
According to your comment, the simplest way would be to add a new property in your Section_Model class named id in which to can store the id of each particular document. So everytime you add a new document, that document will contain the id. Using getItem(position) will return an object of Section_Model class. See the code below:
Section_Model model = getItem(position);
String id = model.getId();
So model.getId() will return the id of the object that was set when you have added that document to the database.
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.
I develop (NEWS Android app) with android studio and I have a problem, I Post a Short topic in the app and I need to let the user see the full topic when clicks on TextView (Click Here), but I need to change the site link on every topic. Anyone can help me, please ??
I Update the news through (Firebase Database and Online Database)
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
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.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.squareup.picasso.Picasso;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
public class Home extends AppCompatActivity {
RequestQueue requestQueue;
String url = "https://mobarmejlebanon.000webhostapp.com/show.php";
TextView textView;
ListView listview;
ArrayList<listitme> listitmes = new ArrayList<listitme>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
textView = (TextView) findViewById(R.id.textView);
listview = (ListView) findViewById(R.id.listview);
requestQueue = Volley.newRequestQueue(this);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("allstudents");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject respons = jsonArray.getJSONObject(i);
String id = respons.getString("id");
String name = respons.getString("name");
String info = respons.getString("info");
String img = respons.getString("img");
listitmes.add(new listitme(id, name, info, img));
listAllItme();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", "ERROR");
}
}
);
requestQueue.add(jsonObjectRequest);
}
public void listAllItme() {
listAdpter lA = new listAdpter(listitmes);
listview.setAdapter(lA);
}
class listAdpter extends BaseAdapter {
ArrayList<listitme> listA = new ArrayList<listitme>();
public listAdpter(ArrayList<listitme> listA) {
this.listA = listA;
}
#Override
public int getCount() {
return listA.size();
}
#Override
public Object getItem(int position) {
return listA.get(position).id;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = getLayoutInflater();
View view = layoutInflater.inflate(R.layout.row_item, null);
TextView id = (TextView) view.findViewById(R.id.textView_id);
TextView name = (TextView) view.findViewById(R.id.textView_name);
TextView info = (TextView) view.findViewById(R.id.textView_info);
ImageView img = (ImageView) view.findViewById(R.id.image);
id.setText(listA.get(position).id);
name.setText(listA.get(position).name);
info.setText(listA.get(position).info);
Picasso.with(Home.this).load("https://mobarmejlebanon.000webhostapp.com/images/" + listA.get(position).img).into(img);
return view;
}
}
}
Here is the Firebase database code
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
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;
public class Topic2 extends AppCompatActivity {
TextView TopicTitle,Topic;
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference mRootReference = firebaseDatabase.getReference();
DatabaseReference mKidRefernece = firebaseDatabase.getReference("topictwotitle");
DatabaseReference mChildReference = mRootReference.child("topictwomessage");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_topic2);
TopicTitle = (TextView) findViewById(R.id.twotitle);
Topic = (TextView) findViewById(R.id.twomsg);
TopicTitle.setText("Please Wait");
Topic.setText("Loading");
}
#Override
protected void onStart() {
super.onStart();
mChildReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String message = dataSnapshot.getValue(String.class);
Topic.setText(message);
mKidRefernece.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String topictitle = dataSnapshot.getValue(String.class);
TopicTitle.setText(topictitle);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
I suggest you to use CardView and RecyclerView in order to achieve your purpose. You can get a better insight of it here:
Also you can catch a glimpse of it in action here and hither.
EDIT
According to the new query regarding this question; I think you must catch up this How to get a text after clicking on the CardView.
Happy Coding...
EDIT
Here is your sample:
I added dummy right now.
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<TopicDTO> topics = new ArrayList<>();
for (int i = 0; i < 10; i++) {
topics.add(new TopicDTO("" + i, "Topic " + (i + 1), "Your Topic info goes here", "Your Topic Image goes here", "http://www.google.com"));
}
ListView listTopics = (ListView) findViewById(R.id.listTopics);
listTopics.setAdapter(new TopicsListAdapter(MainActivity.this, topics));
}
}
TopicsListAdapter.java
public class TopicsListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<TopicDTO> mData;
public TopicsListAdapter(Context context, ArrayList<TopicDTO> data) {
mInflater = LayoutInflater.from(context);
mData = data;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Object getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ChildViewHolder holder;
if (convertView == null) {
holder = new ChildViewHolder();
convertView = mInflater.inflate(R.layout.row_topics, parent,
false);
holder.textTopicTitle = (TextView) convertView
.findViewById(R.id.textTopicTitle);
holder.textTopicInfo = (TextView) convertView
.findViewById(R.id.textTopicInfo);
holder.textTopicLink = (TextView) convertView
.findViewById(R.id.textTopicLink);
convertView.setTag(holder);
} else {
holder = (ChildViewHolder) convertView.getTag();
}
final TopicDTO mItem = mData.get(position);
holder.textTopicTitle.setText(mItem.name);
holder.textTopicInfo.setText(mItem.info);
/*You need to have a more info link per topic*/
holder.textTopicLink.setClickable(true);
holder.textTopicLink.setMovementMethod(LinkMovementMethod.getInstance());
String text = "<a href='" + mItem.moreInfoLink + "'> Click here to see full topic </a>";
holder.textTopicLink.setText(Html.fromHtml(text));
return convertView;
}
class ChildViewHolder {
TextView textTopicTitle, textTopicInfo, textTopicLink;
}
}
row_topics.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:orientation="horizontal">
<ImageView
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/textTopicTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/textTopicInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp" />
</LinearLayout>
</LinearLayout>
<!--You need to add extra TextView in your row file of listview.
It will work as a link per topic.-->
<TextView
android:id="#+id/textTopicLink"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:text="Click here to see full topic" />
</LinearLayout>
Read each comment carefully and then implement it. That's it. Nothing can be better than this.
OLD
You need to have a textView for each topic you have.You have something like listview or recyclerview. Then when user clicks on that textView open link associated with that topic only that is from your dataset of listview.
Try this on your textview on which you want to open a link :
info.setClickable(true);
info.setMovementMethod(LinkMovementMethod.getInstance());
String text = "<a href='http://www.google.com'> Google </a>";
info.setText(Html.fromHtml(text));
Replace "http://www.google.com" with your topic's link.
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>