Hi I am new to JGraphT and am trying to import a graph to work with. I have attached a sample below of the graph and the classes i have set up as the vertex and edges. Hopefully i am doing this the right way.
I am getting the error code:
Caused by: org.jgrapht.nio.ImportException: Failed to parse GraphML
Caused by: java.lang.IllegalArgumentException: http://www.w3.org/2001/XMLSchema
I would love some advice on how to sort this issue and get the graph built. Do i need a Supplier/provider? Do i need to implement a vertex set? Thank you
Vertex Class:
public class Node {
private String id;
private String lat;
private String lon;
private String name;
private String waypointType;
private String levelId;
private String onStartingRoute;
private String onFinishroute;
private String title;
private String description;
private String relatedRoutes;
public Node() {
}
public Node(String id, String lat, String lon, String name, String waypointType, String levelId, String onStartingRoute, String onFinishroute, String title, String description, String relatedRoutes) {
this.id = id;
this.lat = lat;
this.lon = lon;
this.name = name;
this.waypointType = waypointType;
this.levelId = levelId;
this.onStartingRoute = onStartingRoute;
this.onFinishroute = onFinishroute;
this.title = title;
this.description = description;
this.relatedRoutes = relatedRoutes;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLat() {
return lat;
}
public void setLat(String lat) {
this.lat = lat;
}
public String getLon() {
return lon;
}
public void setLon(String lon) {
this.lon = lon;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWaypointType() {
return waypointType;
}
public void setWaypointType(String waypointType) {
this.waypointType = waypointType;
}
public String getLevelId() {
return levelId;
}
public void setLevelId(String levelId) {
this.levelId = levelId;
}
public String getOnStartingRoute() {
return onStartingRoute;
}
public void setOnStartingRoute(String onStartingRoute) {
this.onStartingRoute = onStartingRoute;
}
public String getOnFinishroute() {
return onFinishroute;
}
public void setOnFinishroute(String onFinishroute) {
this.onFinishroute = onFinishroute;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getRelatedRoutes() {
return relatedRoutes;
}
public void setRelatedRoutes(String relatedRoutes) {
this.relatedRoutes = relatedRoutes;
}
#Override
public String toString() {
return "Node{" +
"id='" + id + '\'' +
", lat='" + lat + '\'' +
", lon='" + lon + '\'' +
", name='" + name + '\'' +
", waypointType='" + waypointType + '\'' +
", levelId='" + levelId + '\'' +
", onStartingRoute='" + onStartingRoute + '\'' +
", onFinishroute='" + onFinishroute + '\'' +
", title='" + title + '\'' +
", description='" + description + '\'' +
", relatedRoutes='" + relatedRoutes + '\'' +
'}';
}
public int hashCode(){
return toString().hashCode();
}
public boolean equals(Object o){
return (o instanceof Node)&&(toString().equals(o.toString()));
}
}
Edge Class:
public class Edge {
private String edgeId;
private String weight;
private String alpha;
private String intendedpathlonlat;
private String levelId;
private String type;
public Edge() {
}
public Edge(String edgeId, String weight, String alpha, String intendedpathlonlat, String levelId, String type) {
this.edgeId = edgeId;
this.weight = weight;
this.alpha = alpha;
this.intendedpathlonlat = intendedpathlonlat;
this.levelId = levelId;
this.type = type;
}
public String getEdgeId() {
return edgeId;
}
public void setEdgeId(String edgeId) {
this.edgeId = edgeId;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getAlpha() {
return alpha;
}
public void setAlpha(String alpha) {
this.alpha = alpha;
}
public String getIntendedpathlonlat() {
return intendedpathlonlat;
}
public void setIntendedpathlonlat(String intendedpathlonlat) {
this.intendedpathlonlat = intendedpathlonlat;
}
public String getLevelId() {
return levelId;
}
public void setLevelId(String levelId) {
this.levelId = levelId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
#Override
public String toString() {
return "Edge{" +
"edgeId='" + edgeId + '\'' +
", weight='" + weight + '\'' +
", alpha='" + alpha + '\'' +
", intendedpathlonlat='" + intendedpathlonlat + '\'' +
", levelId='" + levelId + '\'' +
", type='" + type + '\'' +
'}';
}
public int hashCode(){
return toString().hashCode();
}
public boolean equals(Object o){
return (o instanceof Node)&&(toString().equals(o.toString()));
}
}
Graph Class:
public class Graph {
private GraphMLImporter<Node, Edge> graphMLImporter = new GraphMLImporter<>();
private Graph<Node, Edge> venueGraph;
private InputStream file;
private Context context;
public void createWayGraph(Context context) throws IOException {
file = context.getApplicationContext().getAssets().open("route.xml");
graphMLImporter.setEdgeWeightAttributeName("weight");
graphMLImporter.setSchemaValidation(true);
graphMLImporter.importGraph(venueGraph, file);
}
}
Sample - GraphML
<?xml version='1.0' encoding='utf-8'?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
<key attr.name="weight" attr.type="double" for="edge" id="weight" />
<key attr.name="edgeid" attr.type="string" for="edge" id="edgeid" />
<key attr.name="alpha" attr.type="string" for="edge" id="alpha" />
<key attr.name="intendedpathlonlat" attr.type="string" for="edge" id="intendedpathlonlat" />
<key attr.name="levelid" attr.type="string" for="edge" id="levelid" />
<key attr.name="weight" attr.type="long" for="edge" id="weight" />
<key attr.name="type" attr.type="string" for="edge" id="type" />
<key attr.name="relatedroutes" attr.type="string" for="node" id="relatedroutes" />
<key attr.name="description" attr.type="string" for="node" id="description" />
<key attr.name="title" attr.type="string" for="node" id="title" />
<key attr.name="on_finish_route" attr.type="string" for="node" id="on_finish_route" />
<key attr.name="on_starting_route" attr.type="string" for="node" id="on_starting_route" />
<key attr.name="level_id" attr.type="string" for="node" id="level_id" />
<key attr.name="waypoint_type" attr.type="string" for="node" id="waypoint_type" />
<key attr.name="name" attr.type="string" for="node" id="name" />
<key attr.name="lon" attr.type="string" for="node" id="lon" />
<key attr.name="lat" attr.type="string" for="node" id="lat" />
<graph edgedefault="directed" id="Station">
<node id="L08-022">
<data key="lat">40.69330963</data>
<data key="lon">-73.98752537</data>
<data key="name" />
<data key="waypoint_type">escalator</data>
<data key="level_id">1080000</data>
<data key="on_starting_route" />
<data key="on_finish_route" />
</node>
<node id="L08-023">
<data key="lat">40.69318355</data>
<data key="lon">-73.98755793</data>
<data key="name" />
<data key="waypoint_type">stairs</data>
<data key="level_id">1080000</data>
<data key="on_starting_route" />
<data key="on_finish_route" />
</node>
<node id="L08-024">
<data key="lat">40.69316844</data>
<data key="lon">-73.98755873</data>
<data key="name" />
<data key="waypoint_type">stairs</data>
<data key="level_id">1080000</data>
<data key="on_starting_route" />
<data key="on_finish_route" />
</node>
<edge source="WL10-054" target="L10-029">
<data key="type">floor</data>
<data key="weight">4.22</data>
<data key="levelid">1100000</data>
<data key="intendedpathlonlat">[[-73.9874098324427, 40.6923649788941], [-73.9873852113531, 40.6923542068882], [-73.9874280729066, 40.6923105568907], [-73.9874317515063, 40.6923068106214], [-73.9874565632741, 40.692323527741], [-73.9874098324427, 40.6923649788941]]</data>
<data key="alpha">0.0</data>
<data key="edgeid">RL10-059</data>
</edge>
<edge source="WL10-054" target="WL10-053">
<data key="type">floor</data>
<data key="weight">5.69</data>
<data key="levelid">1100000</data>
<data key="intendedpathlonlat">[[-73.9875185331049, 40.6923375058386], [-73.9875194277605, 40.6923108807062], [-73.9874887802005, 40.6923107720732], [-73.9874280729066, 40.6923105568907], [-73.987427278228, 40.6923378450122], [-73.9875185331049, 40.6923375058386]]</data>
<data key="alpha">0.0</data>
<data key="edgeid">RL10-060</data>
</edge>
</graph>
</graphml>
Related
this app doesn't use profile image as profile photo. but i want to add it with firebase.
I want to add/change from icon to user photo profile, data from firebase
I've tried it with the code below, everything in the user list turns into my photo, so it's weird.
please help me what should i do.how to display database(name, photo, status and address) from firebase in listview?
enter image description here
the result is like in this picture, the user photos are all the same
MyActivity Code:
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
getLocation();
View view2 = view;
Object item = getItem(i);
boolean z = item instanceof Channel;
String str = "";
if (z) {
Channel channel = (Channel) item;
if (view2 == null || view2.findViewById(R.id.channelname1) == null) {
view2 = this.inflater.inflate(R.layout.item_channel2, viewGroup, false);
}
TextView textView = (TextView) view2.findViewById(R.id.channelname1);
TextView textView2 = (TextView) view2.findViewById(R.id.chantopic);
ImageView imageView = (ImageView) view2.findViewById(R.id.channelicon);
Button join = (Button) view2.findViewById(R.id.join_btn2);
int icon_resource = R.drawable.inbox;
if(channel.bPassword) {
icon_resource = R.drawable.ic_lock;
imageView.setContentDescription(getString(R.string.text_passwdprot));
imageView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
}
else {
imageView.setContentDescription(null);
imageView.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
}
imageView.setImageResource(icon_resource);
textView.setText(channel.szName);
textView2.setText(channel.szTopic);
int size = Utils.getUsers(channel.nChannelID, MainActivity.this.ttservice.getUsers()).size();
if (size > 0) {
str = String.format("%d ", Integer.valueOf(size));
}
TextView textView3 = (TextView) view2.findViewById(R.id.population);
textView3.setText(str);
if (size > 0) {
str = String.format("%d ", Integer.valueOf(size));
}
if(channel.nParentID == 0) {
// show server name as channel name for root channel
ServerProperties srvprop = new ServerProperties();
ttclient.getServerProperties(srvprop);
textView.setText(srvprop.szServerName);
viewptt.setVisibility(View.GONE);
}
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.join_btn2 : {
joinChannel(channel);
}
break;
}
}
};
join.setOnClickListener(listener);
join.setAccessibilityDelegate(accessibilityAssistant);
join.setEnabled(channel.nChannelID != ttclient.getMyChannelID());
}
else if (item instanceof dk.bearware.User) {
dk.bearware.User user = (dk.bearware.User) item;
if (view2 == null || view2.findViewById(R.id.txtUsername) == null) {
view2 = this.inflater.inflate(R.layout.list_users_grid, viewGroup, false);
}
imgBGWhite = view2.findViewById(R.id.imgBGWhite);
imgOff = view2.findViewById(R.id.imgOff);
imgOn = view2.findViewById(R.id.imgOn);
mImageView = (CircleImageView) view2.findViewById(R.id.imageView);
TextView txtLastDate= (TextView) view2.findViewById(R.id.txtLastDate);
TextView txtLastMsg= (TextView) view2.findViewById(R.id.txtLastMsg);
TextView txtUnreadCounter= (TextView) view2.findViewById(R.id.txtUnreadCounter);
mTxtUsername = (TextView) view2.findViewById(R.id.txtUsername);
status = (TextView) view2.findViewById(R.id.status);
txtLocationCity = (TextView) view2.findViewById(R.id.alamatKota);
txtLastDate.setVisibility(View.GONE);
txtUnreadCounter.setVisibility(View.GONE);
status.setText(status1);
txtLocationCity.setText(location);
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
assert firebaseUser != null;
currentId = firebaseUser.getUid();
reference = FirebaseDatabase.getInstance().getReference(REF_USERS).child(currentId);
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
try {
if (dataSnapshot.hasChildren()) {
final User user = dataSnapshot.getValue(User.class);
assert user != null;
status.setText(user.getAbout());
txtLocationCity.setText(user.getUserAlamatKota());
Utils.setProfileImage(getApplicationContext(), user.getImageURL(), mImageView1);
}
} catch (Exception ignored) {
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
mTxtUsername.setText(Utils.getDisplayName(MainActivity.this.getBaseContext(), user));
try {
int size2 = Utils.getUsers(MainActivity.this.curchannel.nChannelID, MainActivity.this.ttservice.getUsers()).size();
TextView textView11 = MainActivity.this.recUserOnline;
textView11.setText(size2 + str);
textView11.setTextColor(YELLOW);
MainActivity.this.channelSekarang = MainActivity.this.curchannel.nChannelID;
MainActivity.this.textInfoChannel.setText(MainActivity.this.curchannel.szTopic);
TextView textView10 = textChannelSekarang;
textView10.setText(curchannel.szName + str);
} catch (Exception unused3) {
}
boolean talking = (user.uUserState & UserState.USERSTATE_VOICE) != 0;
boolean female = (user.nStatusMode & TeamTalkConstants.STATUSMODE_FEMALE) != 0;
boolean away = (user.nStatusMode & TeamTalkConstants.STATUSMODE_AWAY) != 0;
if(user.nUserID == ttservice.getTTInstance().getMyUserID()) {
talking = ttservice.isVoiceTransmitting();
}
if(talking) {
String name1 = Utils.getDisplayName(getBaseContext(), user);
mTxtUsername.setContentDescription(getString(R.string.user_state_now_speaking, name1));
if(female) {
imgBGWhite.setVisibility(View.VISIBLE);
imgOn.setVisibility(View.VISIBLE);
imgOff.setVisibility(View.GONE);
}
else {
imgBGWhite.setVisibility(View.VISIBLE);
imgOn.setVisibility(View.VISIBLE);
imgOff.setVisibility(View.GONE);
}
}
else{
imgBGWhite.setVisibility(View.GONE);
imgOn.setVisibility(View.GONE);
imgOff.setVisibility(View.GONE);
}
}
view2.setAccessibilityDelegate(MainActivity.this.accessibilityAssistant);
return view2;
}
User code:
public class User implements Serializable {
private String id;
private String username;
private String email;
private String imageURL;
private String status;
private String search;
private String password;
private boolean active;
private boolean typing;
private String typingwith;
private String about;
private String gender;
private String lastSeen;
private String userAlamat;
private boolean isChecked;
private boolean isAdmin;
private boolean isHost;
private boolean isCoHost;
private int userJenis = 0;
private String userNEGARA;
private String userPROVINSI;
private String userKOTA;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getImageURL() {
return imageURL;
}
public void setImageURL(String imageURL) {
this.imageURL = imageURL;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getSearch() {
return search;
}
public void setSearch(String search) {
this.search = search;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public boolean isTyping() {
return typing;
}
public void setTyping(boolean typing) {
this.typing = typing;
}
public String getTypingwith() {
return typingwith;
}
public void setTypingwith(String typingwith) {
this.typingwith = typingwith;
}
public String getAbout() {
return about;
}
public void setAbout(String about) {
this.about = about;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getLastSeen() {
return lastSeen;
}
public void setLastSeen(String lastSeen) {
this.lastSeen = lastSeen;
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean checked) {
isChecked = checked;
}
public boolean isAdmin() {
return isAdmin;
}
public void setAdmin(boolean admin) {
isAdmin = admin;
}
public boolean isHost() {
return isHost;
}
public void setHost(boolean host) {
isHost = host;
}
public boolean isCoHost() {
return isCoHost;
}
public void setCoHost(boolean cohost) {
isCoHost = cohost;
}
public String setUserJenis(int i) {
this.userJenis = i;
return null;
}
public int getUserJenis() {
return this.userJenis;
}
public String getUserAlamatKota() {
return userKOTA;
}
public void setUserAlamatKota(String userKOTA) {
this.userKOTA = userKOTA;
}
#NotNull
#Override
public String toString() {
return "User{" +
"id='" + id + '\'' +
", username='" + username + '\'' +
", email='" + email + '\'' +
", status='" + status + '\'' +
", userKOTA='" + userKOTA + '\'' +
", userPROVINSI='" + userPROVINSI + '\'' +
", userNEGARA='" + userNEGARA + '\'' +
", imageURL='" + imageURL + '\'' +
", status='" + status + '\'' +
", search='" + search + '\'' +
", password='" + password + '\'' +
", active=" + active +
", typing=" + typing +
", typingwith='" + typingwith + '\'' +
", about='" + about + '\'' +
", gender='" + gender + '\'' +
", lastSeen='" + lastSeen + '\'' +
", isChecked=" + isChecked +
'}';
}
}
I'm getting an error trying to run this camel route:
<route>
<from id="_from1" uri="timer:foo?repeatCount=1"/>
<to id="_to3" uri="sql:select nro_servicio, documentodesconexionsap FROM servicio_cab;?dataSource=dataSource"/>
<to id="_to2" uri="bean:com.enelint.pangeaent.GlobalDataController?method=processGlobalData(Exchange)"/>
<marshal id="_marshal1">
<csv/>
</marshal>
<to id="_to1" uri="file:/fs/out?fileName=out.csv"/>
</route>
The stack trace is: Error occurred while running main from: org.apache.camel.test.blueprint.Main.
If I change the marshal to string it creates the output file but obviously with the content not formatted as comma separated.
I'm using Camel version 2.17.
Any help will be appreciated.
UPDATE:
Here is my POJO class:
package com.enelint.pangeaenelint;
import java.util.Date;
import org.apache.camel.dataformat.bindy.annotation.CsvRecord;
import org.apache.camel.dataformat.bindy.annotation.DataField;
#CsvRecord(separator="\\;")
public class ServicioCab {
#DataField(pos=1, required=false)
String documentodesconexionsap;
#DataField(pos=2, required=false)
String nro_cuenta_contrato;
#DataField(pos=3, required=false)
String status;
#DataField(pos=4, required=true)
String motivo_accion;
#DataField(pos=5, required=false, pattern="dd.MM.yyyy")
String fecha_corte_repo;
#DataField(pos=6, required=false)
String hora_corte_repo;
#DataField(pos=7, required=false)
String reemite;
#DataField(pos=8, required=false)
String dias_reemision;
#DataField(pos=9, required=false)
String enviado_sap;
public String getDocumentodesconexionsap() {
return documentodesconexionsap;
}
public void setDocumentodesconexionsap(String documentodesconexionsap) {
this.documentodesconexionsap = documentodesconexionsap;
}
public String getNro_cuenta_contrato() {
return nro_cuenta_contrato;
}
public void setNro_cuenta_contrato(String nro_cuenta_contrato) {
this.nro_cuenta_contrato = nro_cuenta_contrato;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getMotivo_accion() {
return motivo_accion;
}
public void setMotivo_accion(String motivo_accion) {
this.motivo_accion = motivo_accion;
}
public String getFecha_corte_repo() {
return fecha_corte_repo;
}
public void setFecha_corte_repo(String fecha_corte_repo) {
this.fecha_corte_repo = fecha_corte_repo;
}
public String getHora_corte_repo() {
return hora_corte_repo;
}
public void setHora_corte_repo(String hora_corte_repo) {
this.hora_corte_repo = hora_corte_repo;
}
public String getReemite() {
return reemite;
}
public void setReemite(String reemite) {
this.reemite = reemite;
}
public String getDias_reemision() {
return dias_reemision;
}
public void setDias_reemision(String dias_reemision) {
this.dias_reemision = dias_reemision;
}
public String getEnviado_sap() {
return enviado_sap;
}
public void setEnviado_sap(String enviado_sap) {
this.enviado_sap = enviado_sap;
}
}
So, here is the case, in the onPostExecute method I have used a ListView and I have adapted a list adapter in it in order to display the objects (events) in a list view. The problem is that the adapter recognizes the objects but it does not display them in the ListView. I have looked of how to populate an Array of Hashmaps with a List adapter and I am prettu sure that I have done it correctly in my code. I think that the problem might be in the xml file. Any ideas that can guide me to the right direction?
This is my xml file:
<?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">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
<TextView
android:id="#+id/id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textSize="16sp"/>
<TextView
android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip" />
<TextView
android:id="#+id/date"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="start"/>
<TextView
android:id="#+id/time"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="start" />
<TextView
android:id="#+id/time_end"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="start" />
</LinearLayout>
And the .java file:
public class EventsJSONActivity extends ListActivity {
private static String url = "http://mob.students.acg.edu/json3.php";
public static final String TAG_EVENT_INFO = "eventsinfo";
public static final String TAG_ID = "id";
public static final String TAG_TITLE = "title";
public static final String TAG_DATE = "date";
public static final String TAG_TIME = "time";
public static final String TAG_TIME_END = "time_end";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events_json);
new GetEvents().execute();
}
class GetEvents extends AsyncTask<Void,Void,Void> {
ArrayList<HashMap<String,String>> eventList;
ProgressDialog proDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
proDialog = new ProgressDialog(EventsJSONActivity.this);
Log.d("prodialog: ","Setting Message.");
proDialog.setMessage("Please wait...");
Log.d("prodialog: ","Setting cancellable.");
proDialog.setCancelable(false);
Log.d("prodialog: ","Showing...");
proDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
WebRequest webreq = new WebRequest();
String url = "http://mob.students.acg.edu/json3.php";
String jsonStr = webreq.makeWebServiceCall(url,WebRequest.POSTRequest);
Log.d("Response: ", "> " + jsonStr);
eventList = ParseJSON(jsonStr);
Log.d("eventList info: " , eventList.toString());
return null;
}
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#Override
protected void onPostExecute(Void requestresult) {
super.onPostExecute(requestresult);
if (proDialog.isShowing()) {
proDialog.dismiss();
Log.d("prodialog: ","dismissing dialog.");
}
Log.d("Listadapter: ", "eventList: " + eventList.toString());
ListAdapter adapter = new SimpleAdapter(
EventsJSONActivity.this,eventList,
android.R.layout.simple_list_item_1,
new String[] {TAG_ID, TAG_TITLE, TAG_DATE, TAG_TIME, TAG_TIME_END},
new int[] {R.id.id,R.id.title,R.id.date,R.id.time,R.id.time_end});
Log.d("Listadapter: ","data fed");
ListView lv = (ListView)findViewById(android.R.id.list);
lv.setAdapter(adapter);
Log.d("Listadapter: ",adapter.getCount() + " items set");
}//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
private ArrayList<HashMap<String,String>> ParseJSON(String json) {
if (json != null) {
try {
ArrayList<HashMap<String,String>> eventList = new ArrayList<>();
JSONObject jsonObj = new JSONObject(json);
JSONArray events = jsonObj.getJSONArray(TAG_EVENT_INFO);
for (int i = 0; i < events.length(); i++) {
JSONObject j = events.getJSONObject(i);
String id = j.getString(TAG_ID);
String title = j.getString(TAG_TITLE);
String date = j.getString(TAG_DATE);
String time = j.getString(TAG_TIME);
String time_end = j.getString(TAG_TIME_END);
HashMap<String,String> event = new HashMap<String,String>();
event.put(TAG_ID,id);
event.put(TAG_TITLE,title);
event.put(TAG_DATE,date);
event.put(TAG_TIME,time);
event.put(TAG_TIME_END,time_end);
/*event.put(TAG_ID,"id");
event.put(TAG_TITLE,"title");
event.put(TAG_DATE,"date");
event.put(TAG_TIME,"time");
event.put(TAG_TIME_END,"time_end");*/
eventList.add(event);
}
Log.d("EventList > ", eventList.toString());
return eventList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
} else {
Log.e("ServiceHandler", "No data received from HTTP Request");
return null;
}
}
}
}
Try checking the solution that was posted here ... updating ListView from AsyncTask. The runOnUiThread runnable may be what you are missing since the code you have here looks correct. If that doesn't work, you can try creating class levels variables for the listview and/or adapter and modify them in the onPostExecute of AsyncTask.
Hope this helps!
I have a POJO class as below.
import java.util.List;
public class LocationInfoDTO{
private int _id;
private String name;
private String type;
private String fullName;
private int location_id;
private boolean isEurope;
private String countryCode;
private boolean coreCountry;
private int iataAirportCode;
private List<Geospatial> geo_location;
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public int getLocation_id() {
return location_id;
}
public void setLocation_id(int location_id) {
this.location_id = location_id;
}
public boolean isEurope() {
return isEurope;
}
public void setEurope(boolean isEurope) {
this.isEurope = isEurope;
}
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
public boolean isCoreCountry() {
return coreCountry;
}
public void setCoreCountry(boolean coreCountry) {
this.coreCountry = coreCountry;
}
public int getIataAirportCode() {
return iataAirportCode;
}
public void getIataAirportCode(int iataAirportCode) {
this.iataAirportCode = iataAirportCode;
}
#Override
public String toString() {
return "LocationInfoDTO [_id=" + _id + ", name=" + name + ", type="
+ type + ", fullName=" + fullName + ", location_id="
+ location_id + ", isEurope=" + isEurope + ", countryCode="
+ countryCode + ", coreCountry=" + coreCountry
+ ", iataAirportCode=" + iataAirportCode + ", geo_location="
+ geo_location + "]";
}
public List<Geospatial> getGeo_location() {
return geo_location;
}
public void setGeo_location(List<Geospatial> geo_location) {
this.geo_location = geo_location;
}
}
All there will be inside a JSON object, just one thing the geospatial attribute has latitude and longitude and that is a different POJO class.All happens good using GSON fromJSON except the geo-location thing is null;
{"_id":376217,"key":null,"name":"test","fullName":"test, test","geo_position":{"latitude":52.52437,"longitude":13.41053}}
This is a sample JSON.
Triggering in this way
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
JSONArray array = new JSONArray(json);
for(int i=0;i<array.length();i++){
System.out.println("Array:"+gson.fromJson(array.getJSONObject(i).toString(), LocationInfoDTO.class));
EDIT--------------------------------
Changed the geo-location to geo-position
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT
The error says exaclty what's wrong. You have a json object there for geo-location and it expects a list. Even if it's a one element list. Change
{"_id":376217,"key":null,"name":"test","fullName":"test, test","geo_position":{"latitude":52.52437,"longitude":13.41053}}
to
{"_id":376217,"key":null,"name":"test","fullName":"test, test","geo_position":[{"latitude":52.52437,"longitude":13.41053}]}
UPDATE
Since there will always be one lat/long, you should update your POJO so that geo_location is a single GeoSpatial object, not a List<GeoSpatial>
I have a Location class that stores multiple location objects, parsed in from a JSON file. At the moment I can print out all locations in the list by using the toString() method. The output looks like this:
http://hastebin.com/eruxateduz.vhdl
This is an example of one of the loctions within the list:
Location [location=null, id=3, description=You are at battlefield of Jerusalem. You are in awe of your surroundings, you see an exit to the west., weight=100, name=Jerusalem, exit=[Exit [title=Hattin, direction=West]]],
But I'm wondering how I can print out a specific location within that list by the field value id, for example the loction with id="2"?
I'm thinking an override toString method could be created to take an input of id, and print the corresponding location object, but not sure how to print by 'id':
if(LocationObject.getId() == "2") {
//do something
}
This is the POJO Location class that stores the objects:
public class Location {
private Location[] location;
private int id;
private String description;
private String weight;
private String name;
private Exit[] exit;
private boolean visited = false;
private boolean goalLocation;
private int approximateDistanceFromGoal = 0;
private Location parent;
public Location[] getLocation() {
return location;
}
public void setLocation(Location[] location) {
this.location = location;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDescription ()
{
return description;
}
public void setDescription (String description)
{
this.description = description;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
public String getName ()
{
return name;
}
public void setName (String name)
{
this.name = name;
}
public Exit[] getExit() {
return exit;
}
public void setExit(Exit[] exit) {
this.exit = exit;
}
#Override
public String toString() {
return "Location [location=" + Arrays.toString(location) + ", id=" + id
+ ", description=" + description + ", weight=" + weight
+ ", name=" + name + ", exit=" + Arrays.toString(exit)
+"]";
}
}
try checking id's
if(LocationObject.getId() == "2") {
System.out.println(LocationObject.getDescription());
}