I am new to Android. Got a few question regarding the pass back data from Servlet to Android.
So here is my code at servlet:
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
JSONArray jsonArray = new JSONArray();
PrintWriter out = response.getWriter();
String action = request.getParameter("action");
if (action.equalsIgnoreCase("GetAllGame")) {
try {
PreparedStatement statement = db
.getStatement("SELECT * FROM game");
ResultSet result = statement.executeQuery();
while (result.next()) {
JSONObject gameInfo = new JSONObject();
gameInfo.put("gameID", result.getString("gameID"));
gameInfo.put("gameVenue", result.getString("venueID"));
gameInfo.put("gameDate", result.getString("date"));
gameInfo.put("gameCapacity",
result.getString("gameCapacity"));
gameInfo.put("gameCredit",
result.getString("gameCredit"));
gameInfo.put("gameBy", result.getString("gameBy"));
gameInfo.put("gameStart", result.getString("gameStart"));
gameInfo.put("gameEnd", result.getString("gameEnd"));
jsonArray.put(gameInfo);
}
}
catch (JSONException je) {
System.out.println(je.getMessage());
} catch (Exception exc) {
System.out.println(exc.getMessage());
}
out.println(jsonArray.toString());
System.out.println(jsonArray.toString());
out.write(jsonArray.toString());
out.flush();
}
When I launch the servlet, it pop out a website with texts like:
TODO write content
Click here to go My Servlet
Sorry as I am still new and unable to post picture. And when I execute the URL on computer such as http://localhost:8080/WebService/MyServlet?action=GetAllGame , at the console of GlassFish server tab, it did actually print out all the data but nothing is showing on the pop out website.
However, when I ping my phone to my computer and trying to grab the data from my phone, the same thing happens, the data is showing at the console but not on the website in phone. I thought it should be shown on with some json formatted data?
So I thought it was okay until when I implement it into my Android apps, and it is stating that the json passing back from servlet is empty. Any ideas?
What I meant is the data is just printing out from my computer but not actually return back to Android.
Related
I am sending JSON data in rest_v2 to JasperReport Server, to create or modify a user, the Jasper Server page indicates the following structure:
{
"enabled":true,
"password":"newPassword",
"roles":[
{"name":"ROLE_USER"},
{"name":"ROLE_STOREMANAGER", "tenantId":"organization_1"}]
}
There are other additional data, but since they already work for me, I did not put them, here the important thing is the array data, which I have tried several ways but it still does not work for me, this is my code:
JSONObject jsonBodyInfo = new JSONObject();
try {
jsonBodyInfo.put("fullName", "adm");
jsonBodyInfo.put("password", "123");
jsonBodyInfo.put("roles", );
} catch (JSONException e) {
}
I need to add the topic of roles, any help?
Fix the problem by creating an JSONArray outside and passing it in as follows:
JSONArray array = new JSONArray();
array.put(new JSONObject().put("name", "ROLE_USER").put("name", "ROLE_PRUEBA"));
JSONObject jsonBodyInfo = new JSONObject();
try {
jsonBodyInfo.put("fullName", user);
jsonBodyInfo.put("enable", enabled);
jsonBodyInfo.put("password", pwd);
jsonBodyInfo.put("roles", array);
} catch (JSONException e) {
}
I am working on a project right now where I use jsoup in a class with the function retrieveMedia in order to return an ArrayList filled with data from the webpage. I run it in a thread since you shouldn't be connecting to URLs from the main thread. I run it and join it. However, it doesn't work (I tested the same code in Eclipse separate from Android Studio and it worked fine). It seems that no matter what I do I can't get jsoup to connect to the webpage. Below is my class MediaRetriever.
public class MediaRetreiever {
public ArrayList<Media> retrieveMedia() {
ArrayList<Media> mediaOutput = new ArrayList<Media>(); //Store each scraped post
Thread downloadThread = new Thread(new Runnable() {
public void run() {
Document doc = null;
try {
doc = Jsoup.connect(<Website Im connecting to>).timeout(20000).get();
} catch (IOException e) {
System.out.println("Failed to connect to webpage.");
mediaOutput.add(new Media("Failed to connect", "oops", "", "oh well"));
return;
}
Elements mediaFeed = doc.getElementById("main").getElementsByClass("node");
for (Element e : mediaFeed) {
String title, author, imageUrl, content;
title=e.getElementsByClass("title").text().trim();
author=e.getElementsByClass("content").tagName("p").select("em").text().trim();
content=e.getElementsByClass("content").text().replace(author,"").trim();
Media media = new Media(title, author, "", content);
mediaOutput.add(media);
}
}
});
downloadThread.start();
try {
downloadThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
return mediaOutput;
}
}
Running this class's method from another class and it doesn't ever connect. Any ideas?
Since you say that the problem persists only in Android, it looks like that you should add the user agent string to your request - first get the user agent string of a browser that displays correctly the site, and then add it to the request:
doc = Jsoup.connect(<Website Im connecting to>)
.userAgent("your-user-agent-string")
.timeout(20000).get();
And as a sidenote - if you are catching exception, don't print your own error message - print the original message, it may be very useful.
After watching these videos, I'm trying to do the same but I'm finding it very difficult as I'm using the old GUI Builder.
I created a form called Form A. I want those results from the web service to display on the form A and be able to navigate upon clicking any of those images just like what happened inside the video.
I'm using the following methods:
private Map response;
#Override
protected void beforeFormA(Form f) {
getattractive();
ArrayList arr = (ArrayList) response.get("results");
for (Object m:arr){
Map ma = (Map)m;
address =(String) ma.get("formatted_address");
findContainer(f).addComponent(new Label(""+ address ));
}
}
Connection Request:
private void getattractive(){
ConnectionRequest r= new ConnectionRequest(){
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser parse= new JSONParser();
response= parse.parseJSON(new InputStreamReader(input));
}
};
String doc="Johor";
r.setUrl("https://maps.googleapis.com/maps/api/place/textsearch/json?query="+doc+"+city+point+of+interest&language=en&key=api_key");
r.setPost(false);
r.setHttpMethod("GET");
InfiniteProgress prog=new InfiniteProgress();
Dialog dlg=prog.showInifiniteBlocking();
r.setDisposeOnCompletion(dlg);
NetworkManager.getInstance(). addToQueueAndWait(r);
}
First record from the webservice (Attached picture):
Please kindly help.
Regards,
IDE: NetBeans
Desktop OS: Windows 7
Simulator
I'm currently trying to integrate Facebook into my Android application. I've had no problems getting the app to connect and authenticate. But I'm having a little trouble understanding how I can handle data once the onCompleted(Response response) callback method is executed.
The method below works:
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
if (state.isOpened()) {
Log.i(TAG, "Logged in...");
new Request(session, "/me", null, HttpMethod.GET,
new Request.Callback() {
#Override
public void onCompleted(Response response) {
GraphObject graphObject = response.getGraphObject();
JSONObject data = graphObject.getInnerJSONObject();
Log.i(TAG, "My DETAILS: ");
try {
Log.i(TAG, "ID: " + data.getLong("id"));
Log.i(TAG, "Name: " + data.getString("name"));
Log.i(TAG, "Email: " + data.getString("email"));
Log.i(TAG,
"Gender: " + data.getString("gender"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}).executeAsync();
} else if (state.isClosed()) {
Log.i(TAG, "Logged out...");
}
}
When I run my application, Facebook authenticates, the data is retrieved and successfully outputs to the Logcat window. However, I'm at a loss to understand how I can pass the JSONObject back to my fragment for further processing.
Most examples I've looked at online simply set the JSONObject content to views in the fragment, or even less helpful simply say /* Handle response here */ or something similar.
I have another similar method where I want to get a profile image url and download the image, but I can't get the url back to my fragment for further processing.
Should I do something like develop a runnable class that accepts a JSONObject as a parameter and start a separate thread from the onCompleted() method to process it the way I want?
My current goal is to get a list of the users friends who use my app and save their profile pictures for use within the app. Am I going about this the wrong way?
SO if I understand you properly, you are getting all data, you are able to parse the JSON but you are not able to pass the data to your other fragment? Why dont you write to a file, which can be accessible from anywhere?
Why do you want to "DOWNLOAD" the images, that will increase your processing time. Just use this URL: https://graph.facebook.com/"+uid.trim()+"/picture?type=normal Where uid is your users id. Use this in Conjunction with Universal Image Loader to asynchronously load your images in image view. You save your time - you save a headache of manually caching files or saving them on the SD.
But bro, the problem here is that Facebook will stop support to the API you are using by April of 2015. Start porting your app to use the latest facebook API; which however is not so useful in getting users information. Cheers and keep on coding :)
This is my download code. It just starts downloading the file without asking user. I've searched multiple forums and nothing seems to work. This is code is in a backing bean attached to a commandButton.
public void doDownloadFile() {
PrintWriter out = null;
try {
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=test.csv");
out = response.getWriter();
CSVWriter writer = new CSVWriter(out);
List<String[]> stringList = new ArrayList<String[]>();
for (User user : userList) {
String[] string = {user.getEmail(), user.getName(), user.getPassword()};
stringList.add(string);
}
writer.writeAll(stringList);
out.flush();
} catch (IOException ex) {
Logger.getLogger(ViewLines.class.getName()).log(Level.SEVERE, null, ex);
} finally {
out.close();
}
}
This is most likely due to the fact your browser is configured to download files of these types without prompt. The code has nothing to do with it.
The behavior of what to do with a download is 100% local, meaning it's the browser, not you, that determines what to do in that case. Whether the user's browser just dumps the file in a download folder or allows him to save it to a particular spot is entirely up to the browser.
Not much to be done.