I'm using backendless and I'm trying to display my directories in a listview. I'm using Android Studio.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Backendless.setUrl(Defaults.SERVER_URL);
Backendless.initApp(this, Defaults.APPLICATION_ID, Defaults.SECRET_KEY, Defaults.VERSION);
Backendless.Files.listing("/Uploads", "*docs", true, new AsyncCallback<BackendlessCollection<FileInfo>>() {
#Override
public void handleResponse(BackendlessCollection<FileInfo> fileInfoBackendlessCollection) {
Iterator<FileInfo> filesIterator = fileInfoBackendlessCollection.getCurrentPage().iterator();
while (filesIterator.hasNext()) {
FileInfo file = filesIterator.next();
String URL = file.getURL();
String publicURL = file.getPublicUrl();
Date createdOn = new Date(file.getCreatedOn());
String name = file.getName();
String[] info = {URL, publicURL, name};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getListView().getContext(), android.R.layout.simple_list_item_1, info);
getListView().setAdapter(adapter);
}
}
#Override
public void handleFault(BackendlessFault backendlessFault) {
}
});
}
}
It has no error but the app doesn't open. Can anyone help me what to do?
Here is the start for fixing your problem:
#Override
public void handleResponse(BackendlessCollection<FileInfo> fileInfoBackendlessCollection) {
// create a list for your data
List<String> infoList = new ArrayList<>();
Iterator<FileInfo> filesIterator = fileInfoBackendlessCollection.getCurrentPage().iterator();
while (filesIterator.hasNext()) {
FileInfo file = filesIterator.next();
String URL = file.getURL();
String publicURL = file.getPublicUrl();
Date createdOn = new Date(file.getCreatedOn());
String name = file.getName();
// put everything into one string temporarily
// String[] info = {URL, publicURL, name};
String info = URL + " " + publicURL + " " + name;
infoList.add(info);
}
// loop through ALL your data before creating/assigning adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getListView().getContext(), android.R.layout.simple_list_item_1, infoList);
getListView().setAdapter(adapter);
}
Now your adapter is going to get a little more complicated, because you will not want to have everything on one line. You will need to create a layout for your list item. Then you need to use either SimpleAdapter or create a custom class extending BaseAdapter and use that to display your data.
Related
I built a fragment which use data in a web service call to display gridView list. It has about .5 second of delay to actually grab data and display the gridView on xml. Issue is that Everytime I come back from other pages or reorient the view, the delay happens. I don't know what I am missing but should the system save the last view in memory to display before it gets the real data from web service whenever I come back from other pages?
public class fragment_grid_room extends Fragment{
private static final String TAG = fragment_grid_room.class.getName();
public fragment_grid_room() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add this line in order for this fragment to handle menu events.
setRetainInstance(true);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//start async task to display rooms
DisplayGridRooms gridRooms = new DisplayGridRooms();
gridRooms.execute(new String[] { "params" });
View rootView = inflater.inflate(R.layout.fragment_roomgrid, container, false);
//rootView.findViewById(R.id.loadingPanel).setVisibility(View.VISIBLE);
//add current date
TextView dayTV = (TextView) rootView.findViewById(R.id.currentDate);
SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy");
Date now = new Date();
String strDate = sdf.format(now);
Log.d(TAG, "*****strdate"+strDate);
dayTV.setText(strDate);
return rootView;
}
//async task to display rooms
private class DisplayGridRooms extends AsyncTask<String, Void, JSONArray> {
JSONArray jsonArrayRooms;
#Override
protected JSONArray doInBackground(String... url) {
String email = getResources().getString(R.string.temp_login);
String pwd = getResources().getString(R.string.temp_pwd);
String username = "apark#anexinet.com";
webServiceRoom wsRoom = new webServiceRoom();
jsonArrayRooms = wsRoom.getRoomList(email, pwd, username);
//System.out.println("222******returning jsonroom with: "+jsonRoom.length());
return jsonArrayRooms;
}
#Override
protected void onPostExecute(JSONArray jsonArrayRooms) {
ArrayList<roomGrid> room_list = new ArrayList<roomGrid>();
int totalNumRooms=jsonArrayRooms.length();
int availNum=0;
for (int i = 0; i < jsonArrayRooms.length(); i++) {
roomGrid roomObject = new roomGrid();
try {
JSONObject jsonRoom = jsonArrayRooms.getJSONObject(i);
String[] temp = jsonRoom.getString("roomName").split("-");
String[] temp2 = temp[1].split("\\(");
roomObject.setRoomName(temp2[0].trim());
String roomStat = jsonRoom.getString("statusText");
roomObject.setStatus(roomStat);
room_list.add(roomObject);
if(roomStat.toLowerCase().contains("available")){ //count available rooms
availNum+=1;
};
} catch (Exception ex) {
Log.e(TAG, "json array exception for rooms:" + ex);
}
}
final GridView gridView = (GridView) getActivity().findViewById(R.id.gridview_room);
//set availability bar
TextView avalBar = (TextView) getActivity().findViewById(R.id.availableBar);
String availbilityText = "Available "+availNum+" of "+totalNumRooms;
avalBar.setText(availbilityText);
Window window = getActivity().getWindow();
View v = window.getDecorView();
ImageButton imageGrid = (ImageButton) v.findViewById(R.id.gridButton);
imageGrid.setVisibility(View.GONE);
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;
int height = size.y;
int numColFinal = 1;
if (width > 350) {
double numCol = width / 350;
numColFinal = (int) numCol;
}
gridView.setNumColumns(numColFinal);
Log.d(TAG, "screen width, numColFinal=" + width + "," + numColFinal);
// getActivity().findViewById(R.id.loadingPanel).setVisibility(View.GONE);
gridView.setAdapter(new CustomAdaptorRoomGrid(getActivity(), room_list));
//when list is clicked, move to detail page
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Object o = gridView.getItemAtPosition(position);
roomGrid fullObject = (roomGrid)o;
String roomName = fullObject.getRoomName();
Intent intent = new Intent(getActivity(), RoomTimeslotActivity.class)
.putExtra(Intent.EXTRA_TEXT, roomName);
startActivity(intent);
}
});
}
}
}
One way to fix the issue is by storing data in shared preferences every time you close your fragment.
First a little improvement. You can move the code below from onPostExecute() in doInBackground(). And then rather return JSONArray in onPostExecute() you can return your list of roomGrid
List<roomGrid> room_list = new ArrayList<roomGrid>();
int totalNumRooms=jsonArrayRooms.length();
int availNum=0;
for (int i = 0; i < jsonArrayRooms.length(); i++) {
roomGrid roomObject = new roomGrid();
try {
JSONObject jsonRoom = jsonArrayRooms.getJSONObject(i);
String[] temp = jsonRoom.getString("roomName").split("-");
String[] temp2 = temp[1].split("\\(");
roomObject.setRoomName(temp2[0].trim());
String roomStat = jsonRoom.getString("statusText");
roomObject.setStatus(roomStat);
room_list.add(roomObject);
if(roomStat.toLowerCase().contains("available")){
//count available rooms
availNum+=1;
};
}
catch (Exception ex) {
Log.e(TAG, "json array exception for rooms:" + ex);
}
}
In your class RoomGrid (the one you add in your list), add
method toJson() - which creates a JSONObjectinstance representing your data
static method public static RoomGrid from(JSONObject json) - which will create and return an RoomGrid instance (or null if json is null, empty, etc)
In you CustomAdaptorRoomGrid add
- getItems() which will return the list of RoomGrid you supplied when creating the adapter
in your fragment onDestroyView() add:
CustomAdaptorRoomGrid adapter = (CustomAdaptorRoomGrid) gridView.getAdapter();
int length = adapter != null && adapter.getItems() != null ? adapter.getItems().size() : 0;
if (length > 0) {
// create a JSONArray from the list
JSONArray array = new JSONArray();
for (RoomGrid item : adapter.getItems()) {
array.put(item.toJson();
}
// add the value in preferences
SharedPreferences prefs = ...;
prefs.edit().put("YOUR_KEY", array.toString()).apply();
}
And finally in your fragment onViewCreated() check for the array from the shared preferences and revert it to a list of your items and supply them to the adapter.
Then engage your task to download and refresh whatever you need.
I m using this framework, I already trying many times for making this problem, but I cant do it. I already asking on stackoverflow but no one cant help me. Actually I m tried.
I m using this framework : https://github.com/kikoso/Swipeable-Cards
And I m using SimpleCardStackAdapter like this :
for (int i = 0; i < user.length(); i++) {
final JSONObject c = user.getJSONObject(i);
// Storing JSON item in a Variable
String id = c.getString(user_id);
String name = c.getString(username);
final String email = c.getString(text);
String image1 = c.getString(imageUrl);
String range1 = c.getString(range);
String msgId = c.getString(postId);
// adapter.add(new CardModel(name, email, image1));
//Set JSON Data in TextView
Log.i("image1image1image1image1", image1);
// CardModel cardModel = new CardModel(" cardModel", " CardModel", r.getDrawable(R.drawable.picture1));
card = new CardModel(name, email, image1);
card.setOnClickListener(new CardModel.OnClickListener() {
#Override
public void OnClickListener() {
Log.i("Swipeable Cards", "I am pressing the card");
// Intent no = new Intent(HomeListview.this, YayDetailActivity.class);
/// startActivity(no);
}
});
card.setOnCardDimissedListener(new CardModel.OnCardDimissedListener() {
#Override
public void onLike(CardModel card) {
Log.i("Swipeable Cards", "I dislike the card");
}
#Override
public void onDislike(CardModel card) {
Log.i("Swipeable Cards", "I like the card");
// new sendNewYay().execute(sharedToken, card.getTitle());
Toast.makeText(getApplicationContext(), card.getDescription(), Toast.LENGTH_SHORT).show();
}
});
// I m added adapter
adapter.add(card);
mCardContainer.setAdapter(adapter);
}
At the onDislike method, I need to get item name.
in this line : new sendNewYay().execute(sharedToken, name);
I send the item name, But it dont work.
1.How can I get the item name, in this method?
2.I have two button, one of them for onLike method, another one for onDislike Method. Ho can I triggered this two method with my button?
Thank you.
Decleare two variable global as string
String itemname;
try {
JSONArray c = new JSONArray(user.toString());
for (int i = 0 ; i < c.length();i++) {
String id = c.getString(user_id);
String name = c.getString(username);
final String email = c.getString(text);
String image1 = c.getString(imageUrl);
String range1 = c.getString(range);
String msgId = c.getString(postId);
System.out.println("Position : " + "" + i + ""+ c.getString(i));
itemname = name.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Final itemname is " + itemname);
So this project is driving me insane. Thank you to Ahmed Aeon Axan for the last answer. I have never worked with HashTables before but from the all the code I've looked at this should be working. Please tell me why this is not displaying in my listview.
Created in the model.java below
public class Model implements Serializable {
public static final int END_MORNING = 11; // 11:00AM, inclusive
public static final int END_AFTERNOON = 16; // 4:00PM, inclusive
private GregorianCalendar startDate;
private ArrayList<GregorianCalendar> datesSmoked = new ArrayList<GregorianCalendar>();
private ArrayList<String> locationsSmoked = new ArrayList<String>();
private ArrayList<String> locations = new ArrayList<String>();
private ArrayList<String> allIncidents = new ArrayList<String>();
private Set<String> newLocArr = new HashSet<String>(locations);
private SimpleDateFormat sdf = new SimpleDateFormat("E, MMM dd");
private ArrayList<String> times = new ArrayList<String>();
public String [] defaultLocations = {"Home", "Work", "Commuting", "School", "Bar", "Restaurant", "Social Gathering", "Other"};
public String [] eachSmoked;
public Model(GregorianCalendar date){
startDate = date;
for (String s : this.defaultLocations) {
locations.add(s);
}
}
public Model(){
this(new GregorianCalendar()); // now
}
public ArrayList<String> getDates() {
for (int i = 0; i < datesSmoked.size(); i++) {
String s = (sdf.format(i));
times.add(s);
}
return times;
}
public List<String> getPlacesSmoked() {
for (String key : locations) {
newLocArr.add(key+ ": " + Collections.frequency(locationsSmoked, key));
}
return new ArrayList<String>(newLocArr);
}
public ArrayList<String> getAllIncidentsArray() {
for (int i = 0; i < datesSmoked.size(); i++) {
allIncidents.add(getDates().get(i) + ", " + locationsSmoked.get(i));
}
return allIncidents;
}
public ArrayList<String> getlocationsArray() {
return this.locations;
}
public ArrayList<String> getLocationsSmokedArray() {
return this.locationsSmoked;
}
public ArrayList<GregorianCalendar> getDatesSmokedArray() {
return this.datesSmoked;
}
Ends the relevant code for model.java
called into the list view in the Locations Activity below where it is not displaying
public class LocationActivity extends Activity {
public static final String SMOKIN_DATA_FILE = "smokin.dat";
public static Model model = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
restoreModel();
ListView listView = (ListView) findViewById(R.id.location_listview_Id);
ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, model.getPlacesSmoked());
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
}
Essentially Im trying to get the ArrayList locationsSmoked which Displays
Home
Home
Home
Home
School
School
School
School
to display
Home: 4
School: 4
Your locTest list is empty, since it is initialized at the Model creation with empty HashSet test1 which is initialized with empty locations list.
The List(Collection<?>) constructor is copying the values, not the pointer to the collection, as far as I remember
fast solution (not sure if it do the trick actually):
public Model(GregorianCalendar date){
startDate = date;
for (String s : this.defaultLocations) {
locations.add(s);
}
// calling setPlacesSmoked to process data
setPlacesSmoked();
}
public void setPlacesSmoked() {
// assuming that locations list holds the data needed to process
for (String key : locations) {
test1.add(key+ ": " + Collections.frequency(locations, key));
}
}
public List<String> getPlacesSmoked() {
//return locTest;
return new ArrayList<String>(test1);
}
The expected output:
Home: 1
Work: 1
Commuting: 1
School: 1
Bar: 1
Restaurant: 1
Social Gathering: 1
Other: 1
But that depends on the locations contents
public class FareActivity extends Activity {
int fareid;
String Source;
String Dest;
AutoCompleteTextView source;
AutoCompleteTextView dest;
static final String[] SOURCE = new String[] {
"Delhi", "Mumbai", "Agra", "Jaipur};
static final String[] DEST = new String[] {
"Delhi", "Mumbai", "Agra", "Jaipur};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fare);
dest = (AutoCompleteTextView) findViewById(R.id.acdest);
ArrayAdapter<String> dadapter = new ArrayAdapter<String>(this, R.layout.list_item, DEST);
dest.setAdapter(dadapter);
source = (AutoCompleteTextView) findViewById(R.id.acsource);
ArrayAdapter<String> sadapter = new ArrayAdapter<String>(this, R.layout.list_item, SOURCE);
dest.setAdapter(sadapter);
// Fare id calculation
if(Source=="Delhi" && Dest=="Jaipur")
{
fareid=1;
}
else if(Source=="Delhi" && Dest=="Agra")
{
fareid=2;
}
else if(Source=="Delhi" && Dest=="Mumbai")
{
fareid=3;
}
}
I just want to store autocompletetextview 'source' and autocompletetextview 'dest' values to String variable 'Source' and String Variable 'Dest'. I will use both string variables for further processing in my project, so please help me out.
Just use the AutoCompleteTextView method getText() and call toString() on it.
// Fare id calculation
Source = source.getText().toString();
Dest = dest.getText().toString();
if (Source.equals("Delhi") && Dest.equals("Jaipur")) {
fareid=1;
}
else if (Source.equals("Delhi") && Dest.equals("Agra")) {
fareid=2;
}
else if (Source.equals("Delhi") && Dest.equals("Mumbai")) {
fareid=3;
}
You should keep in mind that users can enter everything they want into your AutoCompleteTextView. If you want to perform an action when the user chooses one of the suggested items, add an OnItemSelectedListener with dest.setOnItemSelectedListener().
There is also an error in your code you call dest.setAdapter(sadapter) instead of source.setAdapter(sadapter).
AutoCompleteTextView source = (AutoCompleteTextView) findViewById(R.id.acsource);
String Source = source.getText().toString();
I know similar questions have been asked, but I haven't been able to find a solution that works for me. I've added the code I am using to call the JSON feed and display it in a ListAdapter. I need to get my fields "ShowDate" and "ShowStart" to display in a readable format, not UNIX.
public class Schedule extends ListActivity {
protected EditText searchText;
protected SQLiteDatabase db;
protected Cursor cursor;
protected TextView textView;
protected ImageView imageView;
protected ArrayList<HashMap<String, String>> myList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.schedule);
View layout = findViewById(R.id.gradiant);
GradientDrawable gd = new GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM, new int[] {
0xFF95B9C7, 0xFF06357A });
gd.setCornerRadius(2f);
layout.setBackgroundDrawable(gd);
myList = new ArrayList<HashMap<String, String>>();
JSONObject jsonObjSend = new JSONObject();
JSONObject json = JSONfunctions
.getJSONfromURL("MyAPIURL");
JSONArray current = json.getJSONArray("d");
for (int i = 0; i < current.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = current.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("showid", "" + Html.fromHtml(e.getString("ShowID")));
map.put("name", "" + Html.fromHtml(e.getString("Title")));
map.put("showvenue", "" + e.getString("ShowVenue"));
map.put("subtutle", "" + e.getString("SubTitle"));
map.put("venueid", "" + e.getString("VenueID"));
map.put("showdate", "" + e.getString("ShowDate"));
map.put("showstart", "" + e.getString("ShowStart"));
map.put("showend", "" + e.getString("ShowEnd"));
map.put("image250", "" + e.getString("Image250"));
map.put("aboutartist", "" + Html.fromHtml(e.getString("AboutArtist")));
myList.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, myList,R.layout.line_item,
new String[] { "name", "showdate","showstart", "showvenue", "image250" },
new int[] { R.id.title, R.id.showdate,R.id.showstart,R.id.showvenue, R.id.list_image });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> hashMap = myList.get(position);
// hashMap.put("map", hashMap);
Intent intent = new Intent(getApplicationContext(),
ArtistDetails.class);
intent.putExtra("map", hashMap);
startActivity(intent);
}
});
}
Any suggestions or advice will be greatly appreciated. I've spent way too much time on this for something I assume is fairly simple. Thanks!
Thanks for all the replies. Turns out that this is all I need it to do. It may just be a quick fix, but it works. I needed to put it inside my JSONArray.
String showDate = e.getString("ShowDate");
long epoch = Long.parseLong( showDate );
Date showDatePresent = new Date( epoch * 1000 );
SimpleDateFormat sdf = new SimpleDateFormat("E, MMMM d");
String dateOfShow = sdf.format(showDatePresent);
map.put("showdate", "" + dateOfShow);
Checked out the SimpleDateFormat object.
You can use SimpleDateFormat to parse the date you're given and then to format the way you want it
http://developer.android.com/reference/java/text/SimpleDateFormat.html
Like others have said, to convert a timestamp to a date you use SimpleDateFormat.
Date d = new Date(timestamp);
String formattedDate = new SimpleDateFormat("mm/dd/yy hh:mm:ss").format(d);
But it seems like you don't know where to put it. You will need to set a ViewBinder in your SimpleAdapter object that will display the date in the format you want.
SimpleAdapter adapter = new SimpleAdapter(this, myList,R.layout.line_item,
new String[] { "name", "showdate","showstart", "showvenue", "image250" },
new int[] { R.id.title, R.id.showdate, R.id.showstart, R.id.showvenue, R.id.list_image });
adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
if (columnIndex == cursor.getColumnIndex("showdate")
|| columnIndex == cursor.getColumnIndex("showstart")) {
Date d = new Date(cursor.getLong(columnIndex));
String formattedDate = new SimpleDateFormat("mm/dd/yy hh:mm:ss").format(d);
((TextView) view).setText(formattedDate);
return true;
}
return false;
}
});
setListAdapter(adapter);