Converting UNIX time from Android JSON feed - android

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

Related

Using simpleAdapter with image for listview

I have a little problem with putting an image to a list view using simple adapter. I'm getting the image from my online server(AMAZON). After downloading the image based on the user id, i try to set them in my listview but nothing was display and no error is occured.
Below is my code:
// looping through All applicants
for (int i = 0; i < applicant.length(); i++) {
JSONObject c = applicant.getJSONObject(i);
// Storing each JSON item in variable
String uid = c.getString(TAG_UID);
String name = c.getString(TAG_NAME);
String overall = c.getString(TAG_OVERALL);
String apply_datetime = c.getString(TAG_APPLY_DATETIME);
String photo = c.getString(TAG_PHOTO);
// creating new HashMap
//HashMap<String, String> map = new HashMap<String, String>();
//IMAGE
HashMap<String, Object> map = new HashMap<String, Object>();
// adding each child node to HashMap key (value)
map.put(TAG_UID, uid);
map.put(TAG_NAME, name);
map.put(TAG_OVERALL, overall);
map.put(TAG_APPLY_DATETIME, apply_datetime);
// adding HashList to ArrayList
// applicantsList.add(map);
// LISTING IMAGE TO LISTVIEW
try {
imageURL = c.getString(TAG_PHOTO);
InputStream is = (InputStream) new URL(
"my url link/images/"
+ imageURL).getContent();
d = Drawable.createFromStream(is, "src name");
} catch (Exception e) {
e.printStackTrace();
}
map.put(TAG_PHOTO, d);
// adding HashList to ArrayList
applicantsList.add(map);
}
As you can see, after i download the image. i set to listview using simpleAdapter below:
SimpleAdapter adapter = new SimpleAdapter(
SignUpApplicantActivity.this, applicantsList,
R.layout.list_applicant, new String[] {
TAG_UID, TAG_NAME, TAG_OVERALL,
TAG_APPLY_DATETIME, TAG_PHOTO }, new int[] {
R.id.applicantUid, R.id.applicantName,
R.id.applicantOverall,
R.id.apply_datetime, R.id.list_image });
// updating listView
setListAdapter(adapter);
Did you called notifyDatasetChange() ? your adapter may not be invalidated if you don't call it.
From the SimpleAdapter documentation the image data is expected to be a resource ID or a string (an image URI) - see setViewImage(ImageView,String)
I see 2 solutions:
Provide a URI in the data map, not a drawable.
Implement your own view binder to bind the drawable to the ImageView:
adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Object data, String textRepresentation) {
if(view.getId() == R.id.list_image) {
ImageView imageView = (ImageView) view;
Drawable drawable = (Drawable) data;
imageView.setImageDrawable(drawable);
return true;
}
return false;
}
});
Try
try{
for (int i = 0; i < applicant.length(); i++) {
JSONObject c = applicant.getJSONObject(i);
// Storing each JSON item in variable
String uid = c.getString(TAG_UID);
String name = c.getString(TAG_NAME);
String overall = c.getString(TAG_OVERALL);
String apply_datetime = c.getString(TAG_APPLY_DATETIME);
String photo = c.getString(TAG_PHOTO);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key (value)
map.put(TAG_UID, uid);
map.put(TAG_NAME, name);
map.put(TAG_OVERALL, overall);
map.put(TAG_APPLY_DATETIME, apply_datetime);
map.put(TAG_PHOTO, photo);
// adding HashList to ArrayList
applicantsList.add(map);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
SimpleAdapter adapter = new SimpleAdapter(
SignUpApplicantActivity.this, applicantsList,
R.layout.list_applicant, new String[] {
TAG_UID, TAG_NAME, TAG_OVERALL,
TAG_APPLY_DATETIME, TAG_PHOTO }, new int[] {
R.id.applicantUid, R.id.applicantName,
R.id.applicantOverall,
R.id.apply_datetime, R.id.list_image });
// updating listView
setListAdapter(adapter);
Maybe my code can help you!?!
I have made
convertDrawable(int Integer)
and String.valueOf(convertDrawable(iconId))
HashF.put(TAG_ID, String.valueOf(convertDrawable(iconId)));
private void getList(JSONObject json) {
try {
details = json.getJSONArray(TAG_LIST);
for (int i = 0; i < details.length(); i++) {
JSONObject main = details.getJSONObject(i);
Integer date = main.getInt(TAG_DATE);
JSONArray nArray = main.getJSONArray(TAG_NOW);
JSONObject detail = nArray.getJSONObject(0);
Integer iconId = detail.getInt(TAG_ID);
HashMap<String, String> HashF = new HashMap<String, String>();
HashF.put(TAG_DATE, convertDate(date));
HashF.put(TAG_ID, String.valueOf(convertDrawable(iconId)));
fList.add(HashF);
}
} catch (Exception e) {
}
ListAdapter adapter =
new SimpleAdapter(getActivity(),
fList, R.layout.list_item,
new String[]{
TAG_DATE,
TAG_ID
},
new int[]{
R.id.datum,
R.id.icon_fore
});
setListAdapter(adapter);
}
public static String convertDate(Integer Time) {
SimpleDateFormat sdf =
new SimpleDateFormat(
"dd, MMMM", Locale.getDefault());
Calendar kal =
Calendar.getInstance();
kal.setTimeInMillis(Time * 1000L);
sdf.setTimeZone(kal.getTimeZone());
return sdf.format(kal.getTime());
}
public static int convertDrawable(int aId){
int icon = 0;
if(aId == 8300){
icon = R.drawable.draw1;
}
if (aId >= 7010 && actualId < 7919){
icon = R.drawable.draw2;
}
if (aId >= 2010 && actualId <3010) {
icon = R.drawable.draw3;
}
if (aId >= 3010 && actualId < 4010) {
icon = R.drawable.draw4;
}
if (aId >= 6010 && actualId < 7010) {
icon = R.drawable.draw5;
}
if (aId >= 5010 && actualId < 6010) {
icon = R.drawable.draw6;
}
if (aId == 3801){
icon = R.drawable.draw7;
}
if (aId == 8032){
icon = R.drawable.draw8;
}
if (aId == 8083){
icon = R.drawable.draw9;
}
if (aId == 8704) {
icon = R.drawable.draw10;
}
return icon;
}
Anyway make a look at Bitmap is not a Drawable

How to get a part of a datastring from clicking a listview-item

I have a variable called current which holds the last clicked listview item data. The id of this data is to be used to query the db again for movies taht are similar.
The problem that current = id=17985, title=the matrix, year=1999 when all i need is the actual id-number. I have tried to use substring to only use the correct places of the string. This works for the matrix since its id is exactly 5 digits long, but as soon as i try to click movie with higher/lower amount of digits in its id of course it trips up.
String id = current.substring(4,9).trim().toString(); does not work for all movies.
Heres some code:
// search method: this is necessary cause this is the method thats first used and where the variable current is set. This is also the only method using three lines for getting data - id, title and year.
protected void search() {
data = new ArrayList<Map<String, String>>();
list = new ArrayList<String>();
EditText searchstring = (EditText) findViewById(R.id.searchstring);
String query = searchstring.getText().toString().replace(' ', '+');
String text;
text = searchquery(query);
try {
JSONObject res = new JSONObject(text);
JSONArray jsonArray = res.getJSONArray("movies");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
item = new HashMap<String, String>(2);
item.put("id",jsonObject.getString("id"));
item.put("title",jsonObject.getString("title"));
item.put("year", jsonObject.getString("year"));
data.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
aa = new SimpleAdapter(SearchTab.this, data,
R.layout.mylistview,
new String[] {"title", "year"},
new int[] {R.id.text1,
R.id.text2});
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(aa);
lv.setDividerHeight(5);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
Map<String, String> s = data.get((int) id);
current = s.toString();
}});
}
// similar method: this tries to build a list from the fetched data from "current"-string. As you can see i try to use 4,9 to only get right numbers, but this fails with others. Best would be to only to be ble to get the ID which I cant seem to do. The toast is just to see what is beeing fetched, much like a system out print.
protected void similar() {
data = new ArrayList<Map<String, String>>();
list = new ArrayList<String>();
String id = current.substring(4,9).trim().toString();
Toast.makeText(getApplicationContext(), id, Toast.LENGTH_SHORT).show();
String text;
text = similarquery(id);
try {
JSONObject res = new JSONObject(text);
JSONArray jsonArray = res.getJSONArray("movies");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
item = new HashMap<String, String>(2);
item.put("title",jsonObject.getString("title"));
item.put("year", jsonObject.getString("year"));
data.add(item);
}
} catch (Exception e) {
e.printStackTrace();
}
aa = new SimpleAdapter(SearchTab.this, data,
R.layout.mylistview2,
new String[] {"title", "year"},
new int[] {R.id.text1,
R.id.text2});
ListView lv = (ListView) findViewById(R.id.listView1);
lv.setAdapter(aa);
lv.setDividerHeight(5);
}
Use current.split(",")[0].split("=")[1]
edit - assuming of course that id is always the first in the comma separated list and will always be a name value pair delimited by '='
If you want to solve it via substring then you shouldn't use a predefined .substring(4,9). Use something like that:
String item = "id=17985, title=the matrix, year=1999";
String id = item.substring(item.indexOf("id=") + 3, item.indexOf(" ", item.indexOf("id=") + 3) - 1);
System.out.println("Your ID is: " + id);
// Works also for "test=asdf, id=17985, title=the matrix, year=1999"
It gets the String between "id=" and the next " " (space).

listview onitemclick can't refer

So, i plan to make a listview that if one of its item clicked, it goes to other activity. it's obvious that i want to use intent with extras.
But in my code, the extras is not reffering.
I tried to refer the extras with exact value, it worked, but if I put the extras to refer my object/variable, it won't work.
So far my code goes like this
public class bulan extends ListActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tagihan_list);
Intent i = getIntent();
final String no_pel = i.getStringExtra("no_pel");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("nopel", no_pel));
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
JSON json = new JSON();
JSONObject jobj = json.getJSON("http://10.0.2.2/KP/tagihan.php", pairs);
try {
int length = jobj.getInt("panjang");
for(int n = 1; n <= length; n++){
String m = Integer.toString(n);
JSONObject row = jobj.getJSONObject(m);
String id_tagihan = "No. tagihan : " + row.getString("id");
String bulan = row.getString("bulan");
String tahun = row.getString("tahun");
String tagihan = "Rp. " + row.getString("tagihan");
String status = row.getString("status");
HashMap<String, String> map = new HashMap<String, String>();
map.put("id_tagihan", id_tagihan);
map.put("bulan", bulan);
map.put("tahun", tahun);
map.put("tagihan", tagihan);
map.put("status", status);
list.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(this, list, R.layout.list,
new String[] {"id_tagihan","bulan","tahun","tagihan","status"}, new int[] {
R.id.id_tagihan, R.id.bulan, R.id.tahun, R.id.tagihan, R.id.status});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
String sid = ((TextView) view.findViewById(R.id.id_tagihan)).getText().toString();
String snopel = no_pel;
Intent i = new Intent(bulan.this, rincian.class);
i.putExtra("id", sid);
i.putExtra("no_pel", snopel);
startActivity(i);
}
});
}
}
Like I explained before, it's this part
Intent i = new Intent(bulan.this, rincian.class);
i.putExtra("id", sid);
i.putExtra("no_pel", snopel);
startActivity(i);
that change my code to work if I write them like this
Intent i = new Intent(bulan.this, rincian.class);
i.putExtra("id", "00001");
i.putExtra("no_pel", "0620120001");
startActivity(i);
try
Intent i = new Intent(bulan.this, rincian.class);
Bundle b=new Bundle();
b.putString("id",sid);
b.putString("no_pel",snopel);
i.putExtras(b);
startActivity(i);
In your rincian class get the values as follows.
b=getIntent().getExtras();
String fri_id=b.getString("id");
String nopel=b.getString("no_pel");

Get hashmap out of an Array with Hashmap value X

I have an arraylist with multiple hashmaps that contains information that comes from a sql database
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
This arraylist will eventually fill my listview with items (names of people).
When I click on one item I want to send all of the content of that hashmap to another page.
For example:
John <
Now I want to send the hashmap with all the information of John to another android page.
How do I get that information out of the hashmap?
This is my code:
public class Contactenlijst extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contactview);
ListView lv;
lv = (ListView) findViewById(R.id.list);
lv.setTextFilterEnabled(true);
String[] from = new String[] {"naam"};
int[] to = new int[]{R.id.naam};
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
// Get the data (see above)
JSONObject json = Database
.getJSONfromURL("http://fabian.nostradamus.nu/Android/getcontactinfo.php");
try {
JSONArray contactinfo = json.getJSONArray("contactlijst");
// Loop the Array
for (int i = 0; i < contactinfo.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = contactinfo.getJSONObject(i);
map.put("voornaam", e.getString("staff_name"));
map.put("achternaam", e.getString("staff_lastname"));
map.put("geboortedatum", e.getString("staff_dateofbirth"));
map.put("adres", e.getString("staff_address"));
map.put("postcode", e.getString("staff_address_postal"));
map.put("woonplaats", e.getString("staff_address_city"));
map.put("email", e.getString("staff_email"));
map.put("telefoon", e.getString("staff_phone"));
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
//array for view
ArrayList<HashMap<String, String>> mylist2 = new ArrayList<HashMap<String, String>>();
for(int i = 0; i < mylist.size(); i++){
HashMap<String,String> map2 = new HashMap<String, String>();
map2.put("naam", (mylist.get(i).get("voornaam")+" "+(mylist.get(i).get("achternaam"))));
mylist2.add(map2);
}
try{
lv.setAdapter(new SimpleAdapter(this, mylist2, R.layout.list_item, from, to));
}catch (Exception e){Log.d("test1","test2");}
//onclick stuur array naar contactinfo
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String text = ((TextView) view).getText().toString();
Intent i = new Intent(Contactenlijst.this, Contactinfo.class);
String uittekst[] = text.split(" ");
String voornaam = uittekst[0].toString();
String achternaam = uittekst[1].toString();
startActivity(i);
}
});
}
}
So it all has to happen under "String achternaam = uittekst[1].toString();"
for(Hashmap<String, String> map: mylist) {
for(Entry<String, String> mapEntry: map) {
String key = mapEntry.getKey();
String value = mapEntry.getValue();
}
}

Android: Setting Icon in a list View

Currently, I have json data of several twitter feeds that I parse to fill my list. I have an object, "image" that contains the url of the users icon that I want to set as the ImageView to in the list. I am having trouble trying to figure out how I can take the url and load the image in the Imageview for each row. Here is the code:
public void getTweets(String selection) {
String formatedcat = selection.toLowerCase();
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
JSONObject json = JSONfunctions
.getJSONfromURL("http://example.com/tweet.php");
try {
JSONArray category = json.getJSONArray(formatedcat);
for (int i = 0; i < category.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject c = category.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("name",
c.getString("fullName") + "\n(#" + c.getString("name")
+ ") ");
map.put("text",
c.getString("text") + "\n - "
+ c.getString("timestamp"));
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
ListAdapter adapter = new SimpleAdapter(this, mylist, R.layout.list,
new String[] { "name", "text"}, new int[] { R.id.item_title,
R.id.item_subtitle});
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
}
How to display image from URL on Android
See this question. Look very practical to me. Do that showing of the image in the getView() method where you populate the list and instantiate the child views.

Categories

Resources