Why is my recyclerview only displaying the content of the first item? - android-volley

I am having a problem with my recyclerview, It only displays the content of the first item like this:
I have no idea what caused this, I'm really confused because I have never encountered something like this before. As you can see on the toast, the response return 3 data but I don't understand why the others are not being displayed.
Playlist.java
public class Playlist extends AppCompatActivity {
// inisiasi toolbar
private Toolbar toolbar;
// navigation drawer
public DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
RecyclerView recyclerView;
String[] id,title,dir, artists;
ArrayList<String> artist;
String navTitles[];
TypedArray navIcons;
RecyclerView.Adapter recyclerViewAdapter;
TextView textView;
String video;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playlist);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final Drawable upArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
upArrow.setColorFilter(getResources().getColor(R.color.colorIcons), PorterDuff.Mode.SRC_ATOP);
getSupportActionBar().setHomeAsUpIndicator(upArrow);
Intent intent = getIntent();
video = intent.getStringExtra("songs");
//textView = (TextView) findViewById(R.id.text);
//textView.setText(video);
getPlaylist();
// dir = PlaylistJson.dirs;
//artist = new ArrayList<String>(Arrays.asList(title));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
private void getPlaylist(){
final ProgressDialog loading = ProgressDialog.show(this,"Fetching Data","Please wait...",false,false);
//Creating a string request
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://musicmania.hol.es/playlist/getSongsFromPlaylist",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//If we are getting success from server
Toast.makeText(Playlist.this, response, Toast.LENGTH_LONG).show();
loading.dismiss();
showPlaylistJSON(response);
id = PlaylistJson.ids;
title = PlaylistJson.titles;
artists = PlaylistJson.artists;
recyclerView= (RecyclerView) findViewById(R.id.my_recycler_view);
RecyclerViewAdapter adapter=new RecyclerViewAdapter(id, title,artists, Playlist.this);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(Playlist.this));
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//You can handle error here if you want
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> params = new HashMap<>();
//Adding parameters to request
params.put("playlist", video);
//returning parameter
return params;
}
};
//Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showPlaylistJSON(String json){
PlaylistJson pj = new PlaylistJson(json);
pj.parseJSON();
}
}
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> {
LayoutInflater inflater;
Context context;
String[] id,title, artists;
public RecyclerViewAdapter(String[] id, String[] titles, String[] artists, Context context){
this.id = id;
this.title = titles;
this.artists = artists;
this.context = context;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = null;
RecyclerViewHolder viewHolder = null;
if(Integer.parseInt(id[0]) != 0){
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list, parent, false);
viewHolder = new RecyclerViewHolder(view, context);
}else{
view = LayoutInflater.from(parent.getContext()).inflate(R.layout.empty_list, parent, false);
viewHolder = new RecyclerViewHolder(view, context);
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
if(Integer.parseInt(id[0]) != 0) {
holder.item2.setText(title[position]);
holder.imageView2.setTag(holder);
holder.artist.setText(artists[position]);
}else{
holder.item2.setText(title[position]);
}
}
#Override
public int getItemCount() {
return title.length;
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView item;
ImageView imageView;
TextView item2;
TextView artist;
ImageView imageView2;
ImageButton addtoplaylist;
Context context;
public RecyclerViewHolder(final View itemView, final Context context) {
super(itemView);
this.context = context;
item = (TextView) itemView.findViewById(R.id.tv_NavTitle);
imageView = (ImageView) itemView.findViewById(R.id.iv_NavIcon);
item2 = (TextView) itemView.findViewById(R.id.list_title);
imageView2 = (ImageView) itemView.findViewById(R.id.list_avatar);
artist = (TextView) itemView.findViewById(R.id.list_artist);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), Video.class);
intent.putExtra("video", ParseJson.dirs[getAdapterPosition()]);
v.getContext().startActivity(intent);
}
});
}
}
}
PlaylistJson.java
package com.example.rendell.musicmaniajukebox.json_model;
import android.widget.Toast;
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;
public class PlaylistJson {
public static String[] ids;
public static String[] titles;
public static String[] artists;
public static String[] dirs;
public static final String JSON_ARRAY = "result";
public static final String KEY_ID = "id";
public static final String KEY_TITLE = "title";
public static final String KEY_ARTIST = "artist";
public static final String KEY_DIR = "dir";
private JSONArray users = null;
private String json;
public PlaylistJson(String json){
this.json = json;
}
public void parseJSON(){
JSONObject jsonObject=null;
try {
jsonObject = new JSONObject(json);
users = jsonObject.getJSONArray(JSON_ARRAY);
ids = new String[users.length()];
titles = new String[users.length()];
artists = new String[users.length()];
dirs = new String[users.length()];
for(int i=0;i<users.length();i++){
JSONObject jo = users.getJSONObject(i);
ids[i] = jo.getString(KEY_ID);
titles[i] = jo.getString(KEY_TITLE);
artists[i] = jo.getString(KEY_ARTIST);
dirs[i] = jo.getString(KEY_DIR);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}

So the problem was in my PlaylistJson.java file. My volley response only returns 3 items per set e.g. {"id":1, "title": "song", "artist":"artist"} but I am also initialing for the dir which doesn't receive any json so maybe the bug came from that. Anyway, removed that and it worked.

Related

It takes a long time to load large data in recyclerview

I have 11 text files each containing 50-60 lines. I have read all the files and showed in the recyclerview. I used asynctask to track the progress through the progress bar. I have used log too to see the read lines. I have found that reading is taking short time but after reading, it takes 5-6 seconds to show data in the recyclerview. Why is this causing? What should i do to handle this? Why should i do if there are thousands of text files?
Codes reading files and binding
AsyncTask<Void,Void,Void> task = new AsyncTask<Void, Void, Void>() {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(GrammerDetails.this,
"Loading", "Please Wait for a while");
}
#Override
protected Void doInBackground(Void... voids) {
getFromFilesbagdhara(id,realm);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("first_bagdhara",false);
editor.apply();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
inflateData(listGrammerItem);
progressDialog.dismiss();
}
}.execute();
private void getFromFilesbagdhara(String id, Realm realm) {
String directory = "Grammer/Bagdhara";
AssetManager man = getAssets();
BufferedReader reader = null;
try {
String[] files = man.list(directory);
for (int i =0;i<files.length;i++){
String fileName = files[i];
reader = new BufferedReader(
new InputStreamReader(getAssets().open(directory+"/" + fileName),
"UTF-8"));
String line;
Log.e("File",files[i]);
while ((line = reader.readLine()) != null) {
Log.e("line",line);
// String[] text = line.split(" ");
String a = line.substring(0,line.indexOf("(")-1);
String b = line.substring(line.indexOf("(")+1,line.indexOf(")"));
String wordOne = a;
// String dummyTwo = text[1];
String wordTwo = b; //dummyTwo.substring(1,dummyTwo.length()-1);
final ClassGrammerItem classGrammerItem = new ClassGrammerItem(wordOne,wordTwo,id);
listGrammerItem.add(classGrammerItem);
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
}
private void inflateData(RealmList<ClassGrammerItem> listGrammerItem) {
AdapterGrammerItem adapter = new AdapterGrammerItem(listGrammerItem, GrammerDetails.this);
recyclerView.setAdapter(adapter);
}
Adapter:
public class AdapterGrammerItem extends RecyclerView.Adapter<AdapterGrammerItem
.ViewHolderAdapterRecycler> {
RealmList<ClassGrammerItem> activityList = new RealmList<ClassGrammerItem>();
Context context;
private LayoutInflater layoutInflater;
public AdapterGrammerItem(RealmList<ClassGrammerItem> activityList, Context context) {
this.activityList = activityList;
this.context = context;
layoutInflater = LayoutInflater.from(context);
}
#Override
public AdapterGrammerItem.ViewHolderAdapterRecycler onCreateViewHolder(ViewGroup parent, int viewType) {
View view = layoutInflater.inflate(R.layout.recycler_grammer_item, parent, false);
AdapterGrammerItem.ViewHolderAdapterRecycler viewHolder = new AdapterGrammerItem.ViewHolderAdapterRecycler(view);
return viewHolder;
}
#Override
public void onBindViewHolder(AdapterGrammerItem.ViewHolderAdapterRecycler holder, int position) {
ClassGrammerItem currentItem = activityList.get(position);
holder.wordOne.setText(currentItem.getWordOne());
holder.wordTwo.setText(currentItem.getWordTwo());
}
#Override
public int getItemCount() {
return activityList.size();
}
public class ViewHolderAdapterRecycler extends RecyclerView.ViewHolder {
MyTextView wordOne, wordTwo;
public ViewHolderAdapterRecycler(View itemView) {
super(itemView);
wordOne = (MyTextView) itemView.findViewById(R.id.wordOne);
wordTwo = (MyTextView) itemView.findViewById(R.id.wordTwo);
}
}
}

Adapter showing the wrong images while using Fresco library

i have used fresco library to load images in the adapter. but the images are not set correctly as i expected. Here is my code. please help me. thanks in advance.
public class HomeListingAdapter_recyler1 extends RecyclerView.Adapter {
private Context context;
private ArrayList propertyItemList;
private ImageLoader mImageLoader;
public HomeListingAdapter_recyler1(HomeListingActivity_recycler propertyViews, ArrayList propertyItemList) {
Fresco.initialize(propertyViews);
this.propertyItemList = propertyItemList;
this.context = propertyViews;
}
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.property_item_layout,parent,false);
CustomViewHolder viewHolder = new CustomViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(final CustomViewHolder holder, final int position) {
mImageLoader = VolleySingletonPattern.getInstance(context).getImageLoader();
holder.txtPropertyName.setText(propertyItemList.get(position).ville);
holder.txtPropertyType.setText(propertyItemList.get(position).bienName);
if(propertyItemList.get(position).pieces.equalsIgnoreCase("0")){
holder.txtPropertySurfaceArea.setText(propertyItemList.get(position).surface+" "+context.getString(R.string.meter_square));
}else{ holder.txtPropertySurfaceArea.setText(propertyItemList.get(position).surface+" "+context.getString(R.string.meter_square)+" - "+ propertyItemList.get(position).pieces+" "+context.getResources().getString(R.string.pieces));
}
holder.txtPropertyPrice.setText(propertyItemList.get(position).montantLoyer);
Uri imageUri;
try {
if(!TextUtils.isNullOrEmpty(propertyItemList.get(position).photo)) {
imageUri = Uri.parse(propertyItemList.get(position).photo);
holder.imgPropertyImage.setVisibility(View.VISIBLE);
holder.imgPropertyImage.setImageURI(imageUri);
}
} catch (Exception e) {
}
}
#Override
public int getItemCount() {
return propertyItemList.size();
}
public class CustomViewHolder extends RecyclerView.ViewHolder {
SimpleDraweeView imgPropertyImage;
public TextView txtPropertyName , txtPropertyType , txtPropertySurfaceArea ,txtPropertyPrice;
public CustomViewHolder(View itemView) {
super(itemView);
imgPropertyImage = (SimpleDraweeView) itemView.findViewById(R.id.image_property);
txtPropertyName = (TextView) itemView.findViewById(R.id.txt_property_name);
txtPropertyType = (TextView) itemView.findViewById(R.id.txt_property_type);
txtPropertySurfaceArea = (TextView) itemView.findViewById(R.id.txt_property_surface_piece);
txtPropertyPrice = (TextView) itemView.findViewById(R.id.txt_property_price);
}
}
}
Your imgPropertyImage should be a SimpleDraweeView, not an ImageView.

Recyclerview adapter with asyncTask

I'm trying to use custom adapter with RecyclerView, but the holders are empty. I can't understand what did i miss. Please help.
In MainActivity's AsyncTask:
#Override
protected void onPostExecute(String result) {
json_result = result;
super.onPostExecute(result);
dialog.dismiss();
if (result == null) {
Toast.makeText(MainActivity.this, "error getting results...", Toast.LENGTH_LONG).show();
} else {
try {
JSONObject json = new JSONObject(result);
Log.e(TAG, "create json object");
JSONArray searchArray = json.getJSONArray("Search");
Log.e(TAG, "Search");
for (int i = 0; i < searchArray.length(); i++) {
Log.e(TAG, "run on length");
JSONObject searchObject = searchArray.getJSONObject(i);
Log.e(TAG, "create search object");
String title = searchObject.getString("Title");
Log.e(TAG, "Title" + title);
String type = searchObject.getString("Type");
Log.e(TAG, "Type" + type);
String year = searchObject.getString("Year");
Log.e(TAG, "Year" + year);
String imdbID = searchObject.getString("imdbID");
String poster = searchObject.getString("Poster");
Log.e(TAG, "" + result);
movieList.add(new Movie(title, type, year, imdbID, poster));
Log.e(TAG, "Add to adapter");
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "error parsing results...", Toast.LENGTH_LONG).show();
}
adapter.notifyDataSetChanged();
Log.e(TAG, "Notify");
}
}
Custom Adapter:
public class Adapter extends
RecyclerView.Adapter<Adapter.ViewHolder> {
private LruCache<String, Bitmap> bitmapCache;
Context context;
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView title;
public TextView year;
public TextView type;
public ImageView poster;
public ViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.txt_title);
year = (TextView) itemView.findViewById(R.id.txt_year);
type = (TextView) itemView.findViewById(R.id.txt_rating);
poster = (ImageView) itemView.findViewById(R.id.imageView);
}
}
private List<Movie> mList;
public Adapter(List<Movie> mList) {
this.mList = mList;
int numImages = 4 * 1024 * 1024;
this.bitmapCache = new LruCache<String, Bitmap>(numImages) {
#Override
protected int sizeOf(String key, Bitmap value) {
// this is how to calculate a bitmap size in bytes.
// (bytes-in-a-row * height)
return value.getRowBytes() * value.getHeight();
}
};
}
#Override
public Adapter.ViewHolder onCreateViewHolder
(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View movieView = inflater.inflate(R.layout.card_view, parent, false);
ViewHolder viewHolder = new ViewHolder(movieView);
return viewHolder;
}
#Override
public void onBindViewHolder
(Adapter.ViewHolder holder, int position) {
Movie movie = mList.get(position);
holder.title.setText(movie.getTitle());
holder.year.setText(movie.getYear());
holder.type.setText(movie.getType());
holder.poster.setVisibility(View.INVISIBLE);
GetImageTask task = new GetImageTask(movie, holder);
task.execute(movie.getPoster_url());
}
#Override
public int getItemCount() {
return mList.size();
}
class GetImageTask extends AsyncTask<String, Void, Bitmap> {
private final Movie movie;
private final ViewHolder holder;
public GetImageTask(Movie movie, ViewHolder holder) {
this.movie = movie;
this.holder = holder;
}
#Override
protected Bitmap doInBackground(String... params) {
//download:
String address = params[0];
Bitmap bitmap = HttpHandler.getBitmap(address, null);
//save it in the cache for later:
if (bitmap != null) {
bitmapCache.put(address, bitmap);
}
return bitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
if (movie.equals(holder.poster)) {
holder.poster.setVisibility(View.VISIBLE);
holder.poster.setImageBitmap(result);
}
}
}
}
I think the problem is that my movie class is empty, but i do have JSON results in asynctask...
Your received data , which you have saved in the list -->movieList.
Have you used it in your adapter and set the adapter to the recycler view.
Initialize recycler view in main class
initialize adapter and pass the movielist as arguement to the adapter object created.
attach the adapter to the recyclerview --> recyclerView.setAdapter(adapter).
I think this should work

How to sort column in TableView JavaFx?

I'm trying to sort the columns by clicking the column head. The problem is that he does not sort the column defined as Integer.
I wrote comparator for Integer but I think that this is not the way to sort column.
The code below belongs the client:
public class Client4 extends Application
{ // IO streams
private DataOutputStream toServer = null;
private DataInputStream fromServer = null;
private TableView<Student> tableView = new TableView<Student>();
private ObservableList<Student> data = FXCollections.observableArrayList();
private ComboBox<String> cboStudent = new ComboBox<>();
private ComboBox<String> cboLecturer = new ComboBox<>();
private ArrayList<TableColumn> tableCol = new ArrayList<TableColumn>();
private Callback<TableColumn<Student, String>, TableCell<Student, String>> cellFactory
= (TableColumn<Student, String> p) -> new EditingCell();
#Override // Override the start method in the Application class
public void start(Stage primaryStage) throws Exception
{ // Panel p to hold the label and text field
Button btAddRow = new Button("Add Student");
Button btDeleteRow = new Button("Delete Student");
Button btEdit = new Button("Edit");
Button btAddColumn = new Button("Add Column");
Button btDeleteColumn = new Button("Delete Column");
tableView.setItems(data);
//tableView.setEditable(true);
// Callback<TableColumn<Student, String>, TableCell<Student, String>> cellFactory
// = (TableColumn<Student, String> p) -> new EditingCell();
BorderPane pane = new BorderPane();
pane.setPadding(new Insets(11.5, 12.5, 13.5, 14.5));
HBox hBox = new HBox(20);
hBox.getChildren().addAll(btAddRow, btDeleteRow,
btEdit, btAddColumn, btDeleteColumn);
pane.setTop(hBox);
try {
// #SuppressWarnings("resource")
Socket socket = new Socket("localhost", 8000);
// Create an input stream to receive data from the server
fromServer = new DataInputStream(socket.getInputStream());
// Create an output stream to send data to the server
toServer = new DataOutputStream(socket.getOutputStream());
ArrayList<String> lables = new ArrayList<String>();
int numberRecords=0;
numberRecords = fromServer.readInt();
System.out.println(numberRecords);
while (numberRecords>0)
{ String record =fromServer.readUTF();
lables.add(record);
cboStudent.getItems().add(record);
numberRecords--;
}
for(int i=0; i<lables.size();i++)
{
String lable = lables.get(i);
TableColumn<Student, String> string = new TableColumn<Student, String>(lable);
string.setMinWidth(100);
if (lable.equals("firstName") || lable.equals("lastName") || lable.equals("city") || lable.equals("street") || lable.equals("dept") )
{
string.setCellValueFactory(
new PropertyValueFactory<Student, String>(lable));
defineCell(string);
// ObservableList<String> cbValues = FXCollections.observableArrayList("1", "2", "3");
// string.setCellFactory(ComboBoxTableCell.forTableColumn(new DefaultStringConverter(), cbValues));
tableView.getColumns().add(string);
tableCol.add(string);
}
else if(lable.equals("birthDate"))
{
TableColumn<Student, Date> date = new TableColumn<Student, Date>(lable);
date.setCellValueFactory(
new PropertyValueFactory<Student, Date>(lable));
//defineCell(date);
tableView.getColumns().add(date);
tableCol.add(date);
}
else if(lable.equals("picture"))
{
TableColumn<Student, ImageView> pic = new TableColumn<Student, ImageView>(lable);
pic.setCellValueFactory(
new PropertyValueFactory<Student, ImageView>(lable));
tableView.getColumns().add(pic);
tableCol.add(pic);
}
else
{
TableColumn<Student, Integer> integer = new TableColumn<Student, Integer>(lable);
integer.setCellValueFactory(
new PropertyValueFactory<Student, Integer>(lable));
integer.setSortable(true);
integer.setComparator(new Comparator<Integer>() {
#Override
public int compare(Integer o1, Integer o2) {
if(o1<o2) return 1;
if(o1>o2)return -1;
return 0;
}
});
tableView.getColumns().add(integer);
tableCol.add(integer);
}
}
numberRecords=0;
numberRecords=fromServer.readInt();
while(numberRecords>0)
{ Student student = new Student();
student.setId(fromServer.readUTF());
student.setFirstName(fromServer.readUTF());
student.setLastName(fromServer.readUTF());
student.setCity(fromServer.readUTF());
student.setStreet(fromServer.readUTF());
student.setHouseNumber(fromServer.readUTF());
student.setZipCode(fromServer.readUTF());
student.setBirthDate(fromServer.readUTF());
student.setPicture(fromServer.readUTF());
student.setStartYear(fromServer.readUTF());
student.setDept(fromServer.readUTF());
student.setCredits(fromServer.readUTF());
student.setAverage(fromServer.readUTF());
student.setNumFailed(fromServer.readUTF());
student.setPlace(fromServer.readUTF());
System.out.println(student);
data.add(student);
numberRecords--;
}
tableView.setItems(data);
}
catch (IOException ex) {
}
btEdit.setOnAction(e -> {
editTable(btEdit.toString());
});
pane.setBottom(tableView);
Scene scene = new Scene(pane, 890, 400);
primaryStage.setTitle("ShowCombination"); // Set the stage title
primaryStage.setScene(scene); // Place the scene in the stage
primaryStage.show(); // Display the stage
primaryStage.setAlwaysOnTop(true);
}
private void defineCell(TableColumn<Student, String> string) {
string.setCellFactory(cellFactory);
string.setOnEditCommit(
(CellEditEvent<Student, String> t) -> {
((Student) t.getTableView().getItems().get(
t.getTablePosition().getRow())
).setFirstName(t.getNewValue());
});
ObservableList<String> cbValues = FXCollections.observableArrayList("1", "2", "3");
string.setCellFactory(ComboBoxTableCell.forTableColumn(new DefaultStringConverter(), cbValues));
}
private void editTable(String string) {
tableView.setEditable(true);
Student student=(Student)tableView.getSelectionModel().getSelectedItem();
}
public static void main(String[] args)
{ launch(args);
}
class EditingCell extends TableCell<Student, String> {
private TextField textField;
public EditingCell() {
}
#Override
public void startEdit() {
if (!isEmpty()) {
super.startEdit();
createTextField();
setText(null);
setGraphic(textField);
textField.selectAll();
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
setText((String) getItem());
setGraphic(null);
}
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(getString());
setGraphic(null);
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
textField.focusedProperty().addListener(
(ObservableValue<? extends Boolean> arg0,
Boolean arg1, Boolean arg2) -> {
if (!arg2) {
commitEdit(textField.getText());
}
});
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
}
}
You need to wrap your ObservableList holding the TableView data in a SortedList:
SortedList<Student> sortedItems = new SortedList<>(data);
tableView.setItems(sortedItems);
Next you need to link both together:
sortedItems.comparatorProperty().bind(tableView.comparatorProperty());
And as a friendly side note: Please consider posting a smaller code example showing only what is necessary to demonstrate your problem ;-)
As James_D says, cube root will sort in the same order, but here's a little example you can use to show what you're trying to do
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javafx.application.Application;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.stage.Stage;
public class TableSort extends Application {
#Override
public void start(Stage primaryStage) {
TableView tv = new TableView(FXCollections.observableArrayList(
IntStream.of(1,-2,3,-4,-5,6)
.map(n->{return (int)Math.pow(n, 3);})
.boxed().collect(Collectors.toList())));
TableColumn<Integer, Integer> numCol = new TableColumn("num");
numCol.setCellValueFactory((param) -> {
return new ReadOnlyObjectWrapper<>(param.getValue());
});
TableColumn<Integer, Integer> cbrtCol = new TableColumn("cube root");
cbrtCol.setCellValueFactory((param) -> {
return new ReadOnlyObjectWrapper<>((int)Math.cbrt(param.getValue()));
});
numCol.setComparator((Integer o1, Integer o2) -> {
return Double.compare(Math.cbrt(o1), Math.cbrt(o2));
});
tv.getColumns().addAll(numCol, cbrtCol);
Scene scene = new Scene(tv);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

Volley library throws application exception

I am adding my two separate android activities in one application, one of my activity having volley library but it gives me an exception that appcontroller(volley library) its an application not an activity please help me out
Ya, you have mention in your manifest file appcontroller class as Application. This solves the exception.
Main Acitivity:
public class MainActivity extends FragmentActivity implements OnTabChangeListener, OnPageChangeListener {
MyPageAdapter pageAdapter;
private ViewPager mViewPager;
private TabHost mTabHost;
private Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
// Tab Initialization
initialiseTabHost();
// Fragments and ViewPager Initialization
List<Fragment> fragments = getFragments();
pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
mViewPager.setAdapter(pageAdapter);
mViewPager.setOnPageChangeListener(MainActivity.this);
}
// Method to add a TabHost
private static void AddTab(MainActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec,String message,int picture,Context x)
{
tabSpec.setContent(new MyTabFactory(activity));
View tabIndicator = LayoutInflater.from(x).inflate(R.layout.tab_indicator, tabHost.getTabWidget(), false);
TextView title = (TextView) tabIndicator.findViewById(R.id.title);
title.setText(message);
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
icon.setBackgroundDrawable(x.getResources().getDrawable(picture));
icon.setScaleType(ImageView.ScaleType.FIT_CENTER);
tabSpec.setIndicator(tabIndicator);
tabHost.addTab(tabSpec);
}
// Manages the Tab changes, synchronizing it with Pages
public void onTabChanged(String tag) {
int pos = this.mTabHost.getCurrentTab();
this.mViewPager.setCurrentItem(pos);
for(int i=0;i<mTabHost.getTabWidget().getChildCount();i++)
{
mTabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.BLUE);
//mTabHost.getTabWidget().setDividerDrawable(R.Color.transperant);
}
mTabHost.getTabWidget().getChildAt(mTabHost.getCurrentTab()).setBackgroundColor(Color.CYAN);// selected
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
public void destroyItem(View collection, int position, Object view){
((ViewPager) collection).removeView((ImageView) view);
}
// Manages the Page changes, synchronizing it with Tabs
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
int pos = this.mViewPager.getCurrentItem();
this.mTabHost.setCurrentTab(pos);
}
#Override
public void onPageSelected(int arg0) {
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
// TODO Put here your Fragments
NewSampleFragment f1 = NewSampleFragment.newInstance(getApplicationContext(),R.layout.newfragment_a);
MySampleFragment f2 = MySampleFragment.newInstance("Sample Fragment 2");
MySampleFragment f3 = MySampleFragment.newInstance("Sample Fragment 3");
MySampleFragment f4 = MySampleFragment.newInstance("Sample Fragment 4");
MySampleFragment f5 = MySampleFragment.newInstance("Sample Fragment 5");
fList.add(f1);
fList.add(f2);
fList.add(f3);
fList.add(f4);
fList.add(f5);
return fList;
}
// Tabs Creation
private void initialiseTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
// TODO Put here your Tabs
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab1").setIndicator("Tab1"),"Grocery",R.drawable.movies,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab2").setIndicator("Tab2"),"Crockery",R.drawable.artist,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab3"),"Foods",R.drawable.song,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab4"),"Drinks",R.drawable.shopping,getApplicationContext());
MainActivity.AddTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab5"),"Toys",R.drawable.play,getApplicationContext());
mTabHost.setOnTabChangedListener(this);
}
}
OfferActivity (This should be open when button pressed)
public class OfferActivity extends Activity
{
private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private ProgressDialog pDialog;
private String URL_FEED = "http://nusdtech.com/public_html/checking2.php";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
listView = (ListView) findViewById(R.id.list);
feedItems = new ArrayList<FeedItem>();
listAdapter = new FeedListAdapter(this, feedItems);
listView.setAdapter(listAdapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
// These two lines not needed,
// just to get the look of facebook (changing background color & hiding the icon)
getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
//getActionBar().setIcon(
// new ColorDrawable(getResources().getColor(android.R.color.transparent)));
JsonArrayRequest movieReq = new JsonArrayRequest(URL_FEED,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
hidePDialog();
// Parsing json
for (int i = 0; i < response.length(); i++) {
try {
JSONObject obj = response.getJSONObject(i);
FeedItem movie = new FeedItem();
movie.setId(obj.getInt("id"));
movie.setName(obj.getString("name"));
// Image might be null sometimes
String image = obj.isNull("image") ? null : obj
.getString("image");
movie.setImge(image);
movie.setStatus(obj.getString("status"));
movie.setProfilePic(obj.getString("profilePic"));
//movie.setTimeStamp(obj.getString("price"));
movie.setPrice(obj.getString("price"));
movie.setDate(obj.getString("dates"));
feedItems.add(movie);
} catch (JSONException e) {
e.printStackTrace();
}
}
// notifying list adapter about data changes
// so that it renders the list view with updated data
listAdapter.notifyDataSetChanged();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(movieReq);
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
AppController:
public class AppController extends Application {
public static final String TAG = AppController.class.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
LruBitmapCache mLruBitmapCache;
private static AppController mInstance;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
getLruBitmapCache();
mImageLoader = new ImageLoader(this.mRequestQueue, mLruBitmapCache);
}
return this.mImageLoader;
}
public LruBitmapCache getLruBitmapCache() {
if (mLruBitmapCache == null)
mLruBitmapCache = new LruBitmapCache();
return this.mLruBitmapCache;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Activity that contain fragment buttons
public class NewSampleFragment extends Fragment {
private static View mView;
private Context con;
public static final NewSampleFragment newInstance(Context con,int layout) {
NewSampleFragment f = new NewSampleFragment();
con=con;
Bundle b = new Bundle();
b.putInt("mylayout",layout);
f.setArguments(b);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int layout = getArguments().getInt("mylayout");
mView = inflater.inflate(R.layout.newfragment_a, container, false);
Button button = (Button) mView.findViewById(R.id.bactivity);
Button offer=(Button) mView.findViewById(R.id.aactivity);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent myIntent = new Intent(getActivity(), ListViewDemo.class);
//Optional parameters
getActivity().startActivity(myIntent);
Log.e("Error","Kashif");
}
});
offer.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
startApplication("uzair.sabir.app.OfferActivity");
}
});
return mView;
}
public void startApplication(String application_name){
try{
Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
List<ResolveInfo> resolveinfo_list = getActivity().getPackageManager().queryIntentActivities(intent, 0);
for(ResolveInfo info:resolveinfo_list){
if(info.activityInfo.packageName.equalsIgnoreCase(application_name)){
launchComponent("uzair.sabir.app", "OfferActivity");
break;
}
}
}
catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), "There was a problem loading the application: "+application_name,Toast.LENGTH_SHORT).show();
Log.e("Error",e.getMessage());
}
}
private void launchComponent(String packageName, String name){
Intent launch_intent = new Intent("android.intent.action.MAIN");
launch_intent.addCategory("android.intent.category.LAUNCHER");
launch_intent.setComponent(new ComponentName(packageName, name));
launch_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getActivity().startActivity(launch_intent);
}
}

Resources