I need a help with some networking.
What i am trying to do is to send request to servlet from android and then servlet sends the response back to me.
Here is my code
GSP Client Activity
package com.gps.gpsclient;
import microsoft.mappoint.TileSystem;
import org.osmdroid.api.IProjection;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class GPSClientActivity extends Activity {
private MapView view;
private MapDrawer mainDrawer;
private Intent intent;
private MapController mapController;
private static final String RequestorUrl="http://192.168.1.104:8080/Requestor/RQSRV";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gps);
view = (MapView) findViewById(R.id.mapView);
view.setTileSource(TileSourceFactory.MAPNIK);
view.setBuiltInZoomControls(true);
mapController = view.getController();
mapController.setZoom(10);
GeoPoint point2 = new GeoPoint(51496994, -134733);
mapController.setCenter(point2);
mainDrawer=new MapDrawer(view);
final Button button = (Button) findViewById(R.id.addButton);
button.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
intent=new Intent(GPSClientActivity.this,WaypointSetupActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivityForResult(intent,1);
return false;
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK)
{
final MapPoint point=(MapPoint) data.getSerializableExtra("result");
GeoPoint point2 = new GeoPoint(51496994, -134254);
point.setGeo(point2);
view.setOnTouchListener(new View.OnTouchListener()
{
boolean added=false;
#Override
public boolean onTouch(View v, MotionEvent e)
{
if(!added)
{
IProjection project = view.getProjection();
final GeoPoint geo = (GeoPoint)project.fromPixels((int)e.getX(),(int)e.getY());
mainDrawer.addGeopointToMap(point.getName(), point.getDesc(), geo);
added=true;
Toast.makeText(view.getContext(), "Waypoint "+point.getName()+" was added to Map ", Toast.LENGTH_LONG).show();
DBAccessManager manager=new DBAccessManager();
manager.AddWaypointToDb(point.getName(), point.getDesc(), 1, 1, geo.getLatitudeE6(), geo.getLongitudeE6());
}
return false;
}});
}
}
}
DBAccessManager class
package com.gps.gpsclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.concurrent.ExecutionException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import android.os.AsyncTask;
public class DBAccessManager extends AsyncTask <DBManagerParams, Void,String>
{
//public static final String Url="http://192.168.1.104:8080/Requestor/RQSRV";
public static final String Url="http://158.193.82.6:8080/Requestor/RQSRV";
public DBAccessManager()
{
}
public void AddWaypointToDb(String name,String desc,int Type,int Priority,long Latitude,long Longtitude)
{
String[] headers=new String[10];
String[] headers_values=new String[10];
headers[0]="type of command";
headers_values[0]="insert waypoint";
headers[1]="name";
headers_values[1]=name;
headers[2]="decription";
headers_values[2]=desc;
headers[3]="type";
headers_values[3]=Integer.toString(Type);
headers[4]="priority";
headers_values[4]=Integer.toString(Priority);
headers[5]="latitude";
headers_values[5]=Long.toString(Latitude);
headers[6]="longtitude";
headers_values[6]=Long.toString(Longtitude);
String response = null;
DBManagerParams params=new DBManagerParams(Url,headers,headers_values);
try
{
response=execute(params).get();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println(response);
}
private String readOutput(InputStream in)
{
StringBuffer outputBuffer = new StringBuffer("");
try
{
BufferedReader buffer = new BufferedReader(new InputStreamReader(in));
String s = "";
while ((s = buffer.readLine()) != null)
outputBuffer.append(s);
}
catch (IOException e)
{
e.printStackTrace();
}
return outputBuffer.toString();
}
private InputStream getHttpOutConnection(String urlString,String[] headers,String[]header_values) {
InputStream stream=null;
URL url = null;
try {
url = new URL(urlString);
System.out.println(""+urlString);
URLConnection connection= url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setDoOutput(true);
httpConnection.setDoInput(true);
httpConnection.setRequestMethod("POST");
if (headers.length !=header_values.length)
{
System.err.println("Bad use of headers in :"+this.getClass().toString()+" Method: "+ this.getClass().getEnclosingMethod().getName());
}
else
{
for(int i =0;i<headers.length;i++)
{
if (headers[i]!=null)
httpConnection.setRequestProperty(headers[i], header_values[i]);
}
httpConnection.setReadTimeout(10000 /* milliseconds */);
httpConnection.setConnectTimeout(15000 /* milliseconds */);
httpConnection.setDoInput(true);
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
System.out.println("HTTP OK");
stream=httpConnection.getInputStream();
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return stream;
}
#Override
protected String doInBackground(DBManagerParams... params) {
String response;
response=readOutput(getHttpOutConnection(params[0].URL,params[0].headers,params[0].headers_values));
return response;
}
}
class DBManagerParams
{
String URL;
String[]headers;
String[]headers_values;
String response;
DBManagerParams(String URL,String[]headers,String[]headers_values)
{
this.URL=URL;
this.headers=headers;
this.headers_values=headers_values;
}
}
Servlet side
package Applications;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet(name = "/RQSRV", urlPatterns = {"/RQSRV"})
public class RQSRV extends HttpServlet {
private static final long serialVersionUID = 1L;
private DBConnectionManager DBmanager;
public RQSRV() {
super();
DBmanager=new DBConnectionManager();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
System.out.println("Get was called");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
if (response.getHeader("type of command").equals("insert waypoint"))
{
String name,desc;
int type,prio;
long latitude,longtitude;
name=response.getHeader("name");
desc=response.getHeader("description");
type=Integer.parseInt(response.getHeader("type"));
prio=Integer.parseInt(response.getHeader("priority"));
latitude=Long.parseLong(response.getHeader("latitude"));
longtitude=Long.parseLong(response.getHeader("longtitude"));
DBmanager.Connect();
String command="insert into waypoints values("+(DBmanager.getMaxWaypointId()+1)+",0,"+name+","+desc+","+prio+","+latitude+","+longtitude+")";
DBmanager.ExecuteQueryWithoutResults(command);
}
}
}
App stops working while i call httpConnection.connect().
It is just trying to connect and then after a while it stops on connection timeout.
Things i check:
Servlet is running, and it's accesible from Web Browser
All firewals are stopped
Url of servlet is right
I hope you know what it should be
in your server servlet side you are using "response" to get the data sending by Android?
To get the data is "request"
if (request.getHeader("type of command")!=null && request.getHeader("type of command").equals("insert waypoint"))
{
String name,desc;
int type,prio;
long latitude,longtitude;
name=request.getHeader("name");
desc=request.getHeader("description");
type=Integer.parseInt(request.getHeader("type"));
prio=Integer.parseInt(request.getHeader("priority"));
latitude=Long.parseLong(request.getHeader("latitude"));
longtitude=Long.parseLong(request.getHeader("longtitude"));
DBmanager.Connect();
String command="insert into waypoints values("+(DBmanager.getMaxWaypointId()+1)+",0,"+name+","+desc+","+prio+","+latitude+","+longtitude+")";
DBmanager.ExecuteQueryWithoutResults(command);
//important send status ok to ANDROID to prevent timeout.
response.setStatus(HttpServletResponse.SC_OK);
}else{
//important send status ok to ANDROID to prevent timeout.
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}
Related
When I navigate to the activity that should load a ListView from a JSON hosted on AWS S3, I get nothing but a blank activity. There's no error message, no errors in the debugger, and Logcat doesn't seem to hold any relevant information.
Here's LoadJSONTask.java:
package com.teamplum.projectapple;
import android.os.AsyncTask;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.teamplum.projectapple.NewsDO;
import com.teamplum.projectapple.Response;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
public class LoadJSONTask extends AsyncTask<String, Void, Response> {
public LoadJSONTask(Listener listener) {
mListener = listener;
}
public interface Listener {
void onLoaded(List<NewsDO> androidList);
void onError();
}
private Listener mListener;
#Override
protected Response doInBackground(String... strings) {
try {
String stringResponse = loadJSON(strings[0]);
Gson gson = new Gson();
return gson.fromJson(stringResponse, Response.class);
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (JsonSyntaxException e) {
e.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(Response response) {
if (response != null) {
mListener.onLoaded(response.getAndroid());
} else {
mListener.onError();
}
}
private String loadJSON(String jsonURL) throws IOException {
URL url = new URL(jsonURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = in.readLine()) != null) {
response.append(line);
}
in.close();
return response.toString();
}
}
and here's MainActivity.java:
package com.teamplum.projectapple;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
//import com.teamplum.projectapple.NewsDO;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoadJSONTask.Listener, AdapterView.OnItemClickListener {
private ListView mListView;
public static final String URL = "https://s3-eu-west-1.amazonaws.com/tyi-work/Work_Experience.json";
private List<HashMap<String, String>> mAndroidMapList = new ArrayList<>();
private static final String KEY_TIT = "title";
private static final String KEY_CAT = "category";
private static final String KEY_DES = "description";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = findViewById(R.id.list_view);
mListView.setOnItemClickListener(this);
new LoadJSONTask(this).execute(URL);
}
#Override
public void onLoaded(List<NewsDO> androidList) {
for (NewsDO work : androidList) {
HashMap<String, String> map = new HashMap<>();
map.put(KEY_TIT, work.getTitle());
map.put(KEY_CAT, work.getCategory());
map.put(KEY_DES, work.getDescription());
mAndroidMapList.add(map);
}
loadListView();
}
#Override
public void onError() {
Toast.makeText(this, "Error !", Toast.LENGTH_SHORT).show();
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(this, mAndroidMapList.get(i).get(KEY_TIT),Toast.LENGTH_LONG).show();
}
private void loadListView() {
ListAdapter adapter = new SimpleAdapter(MainActivity.this, mAndroidMapList, R.layout.list_item,
new String[] { KEY_CAT, KEY_TIT, KEY_DES },
new int[] { R.id.version,R.id.name, R.id.api });
mListView.setAdapter(adapter);
}
}
I used this tutorial to help make this, if you need any extra information please feel free to ask, thank you.
I have tested the async task for the URL connection and its working fine.
The problem is either on the parsing or on the activity side. Have you tried putting breakpoints and follow the data?
I am planning to make a news app. I have created a simple search view inside the action bar of my app.
This is the Main activity
package com.example.hp.simplenews;
import android.app.Activity;
import android.app.LoaderManager;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<News>> {
private int Newsloaderid = 1;
private Newsadapter newslistadapter;
private String search_query_input = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView newslistview = findViewById(R.id.list);
newslistadapter = new Newsadapter(this, new ArrayList<News>());
newslistview.setAdapter(newslistadapter);
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(Newsloaderid, null, MainActivity.this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the options menu from XML
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
// Assumes current activity is the searchable activity
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String newtext) {
search_query_input = newtext;
return true;
}
#Override
public boolean onQueryTextChange(String query) {
return true;
}
});
return true;
}
#Override
public Loader<List<News>> onCreateLoader(int i, Bundle bundle) {
return new NewsLoader(this, search_query_input);
}
#Override
public void onLoadFinished(Loader<List<News>> loader, List<News> news) {
newslistadapter.clear();
if (news != null && !news.isEmpty()) {
newslistadapter.addAll(news);
}
}
#Override
public void onLoaderReset(Loader loader) {
newslistadapter.clear();
}
}
The SearchResultsActivity handles the HTTP request and JSON parsing.
This is the SearchResultsActivity
package com.example.hp.simplenews;
import android.app.Activity;
import android.app.LoaderManager;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public class SearchResultsActivity extends Activity{
String query_string = "";
private static final String LOG_TAG = SearchResultsActivity.class.getName();
public static URL createUrl(String query_url) throws MalformedURLException {
URL url = null;
String APIKey = "apiKey";
String query = "q";
try {
final String base_url = "https://newsapi.org/v2/everything?";
Uri final_url = Uri.parse(base_url).buildUpon()
.appendQueryParameter(query, query_url)
.appendQueryParameter(APIKey, "48f67c1e66994aa8a92f92a48b5f6581")
.build();
url = new URL(final_url.toString());
Log.i(LOG_TAG, "THE FINAL URL IS" + final_url);
} catch (MalformedURLException e) {
e.printStackTrace();
Log.e(LOG_TAG, "the url couldn't be made");
}
return url;
}
private static final String HTTPREQUEST(URL url) throws IOException {
String jsonresponse = "";
if (jsonresponse == null) {
return null;
}
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(150000);
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
inputStream = httpURLConnection.getInputStream();
jsonresponse = readfromstream(inputStream);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
inputStream.close();
}
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
return jsonresponse;
}
private static final String readfromstream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String urlline = bufferedReader.readLine();
while (urlline != null) {
output.append(urlline);
urlline = bufferedReader.readLine();
}
return output.toString();
}
private static List<News> JSONParser(String NewsJSON) throws JSONException {
if (TextUtils.isEmpty(NewsJSON)) {
return null;
}
List<News> news = new ArrayList<>();
try {
JSONObject basejson = new JSONObject(NewsJSON);
JSONArray articles = basejson.getJSONArray("articles");
for (int i = 0; i < articles.length(); i++) {
News newss = new News();
JSONObject c = articles.getJSONObject(i);
JSONObject source = c.getJSONObject("source");
newss.setMsource(source.getString("name"));
newss.setMtitle(c.getString("title"));
newss.setMdescription(c.getString("description"));
newss.setMtime(c.getString("publishedAt"));
String image = c.getString("urlToImage");
if (image != null) {
newss.setmImage(c.getString("urlToImage"));
}
newss.setNewsURL(c.getString("url"));
news.add(newss);
}
} catch (JSONException j) {
Log.e(LOG_TAG, "couldn't parse jSON");
}
return news;
}
public static List<News> fetchnews(String search_query) throws IOException, JSONException {
URL url = createUrl(search_query);
String JSONRESPONSE = null;
try {
JSONRESPONSE = HTTPREQUEST(url);
} catch (IOException j) {
j.printStackTrace();
}
List<News> news = JSONParser(JSONRESPONSE);
return news;
}
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
try {
handleIntent(intent);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
private void handleIntent(Intent intent) throws MalformedURLException {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
query_string = intent.getStringExtra(SearchManager.QUERY);
Log.i(LOG_TAG, "The querytext is" + query_string);
}
}
}
This whole process of refreshing the list view is done by a AsyncTaskLoader
The custom Asyntaskloader class is copied below:
public class NewsLoader extends AsyncTaskLoader<List<News>> {
private String mUrl;
private static String LOG_TAG = NewsLoader.class.getName();
public NewsLoader(Context context, String url) {
super(context);
mUrl = url;
}
#Override
protected void onStartLoading() {
forceLoad();
}
#Override
public List<News> loadInBackground() {
if (mUrl == null) {
return null;
}
List<News> news = null;
try {
news = SearchResultsActivity.fetchnews(mUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return news;
}
}
Now I have the search query entered by the user stored in the search_query_input variable in the MainActivity.
But the app just gets stuck when I press the submit button. The override methods for the asynctaskloader are not getting executed at all.
What is happening? Any help will be much appreciated.
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
onQueryTextChange(String newText){
//when user type in searchview get string as newText parameter
asynTaskMethod(newText);
}
onQueryTextSubmit(String query){
//when user press submit button in searchview get string as query parameter
asynTaskMethod(query);
}
});
I am developing an Andriod app to access database using java-servlet.
As I'm using sdk 23 some previous modules are deprecated, so I'm using URLconnection class to get connection to servlet.
But By running below code, my app stops working.
App is built upon Navigation drawer activity and below code is implemented in one fragment class. And yes I've set permissions for network
package com.example.nirmal.gaminghub;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.lang.Object;
public class GameList extends Fragment {
TextView gm_lst=(TextView)getView().findViewById(R.id.game_list);
Button show;
String str ="" ;
public GameList() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
new AsyncTask<String, String, String>() {
protected String doInBackground(String... url) {
try {
URL openUrl = new URL("http://localhost:8080/GamingHub/ShowDataServlet");
HttpURLConnection connection = (HttpURLConnection) openUrl.openConnection();
connection.setDoInput(true);
// Toast.makeText(getApplicationContext(),"hello",Toast.LENGTH_LONG).show();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder getOutput = new StringBuilder();
while ((line = br.readLine()) != null) {
getOutput.append(line);
}
br.close();
str=line;
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
protected void OnPostExecute(String otpt)
{
gm_lst.setText(otpt);
}
}.execute();
gm_lst.setText(str);
return inflater.inflate(R.layout.fragment_game_list, container, false);
}
}
Below code is for servlet, which is working perfectly.
package com.gaming_hub;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ShowDataServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, ClassNotFoundException, SQLException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/gaming_hub","root","");
String sql="SELECT * from games";
PreparedStatement ps=con.prepareStatement(sql);
ResultSet rs=ps.executeQuery();
// DataOutputStream dout=new DataOutputStream();
while(rs.next())
{
out.println(rs.getString(1));
}
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (ClassNotFoundException ex) {
Logger.getLogger(ShowDataServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(ShowDataServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
processRequest(request, response);
} catch (ClassNotFoundException ex) {
Logger.getLogger(ShowDataServlet.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(ShowDataServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
The stack trace would probably clearly point out that the problem is with the code line:
TextView gm_lst=(TextView)getView().findViewById(R.id.game_list);
The problem has to do with the Fragment lifecycle. You just can't (succesfully) call findViewById() at that point as the Fragment and its views don't really exist yet.
For example the onViewCreated() method would be a safe place to call findViewById(). So you could try something like:
public class GameList extends Fragment {
TextView gm_lst;
Button show;
String str ="" ;
public GameList() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_game_list, container, false);
}
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
gm_lst = (TextView)getView().findViewById(R.id.game_list);
new AsyncTask<String, String, String>() {
protected String doInBackground(String... url) {
try {
URL openUrl = new URL("http://localhost:8080/GamingHub/ShowDataServlet");
HttpURLConnection connection = (HttpURLConnection) openUrl.openConnection();
connection.setDoInput(true);
// Toast.makeText(getApplicationContext(),"hello",Toast.LENGTH_LONG).show();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
StringBuilder getOutput = new StringBuilder();
while ((line = br.readLine()) != null) {
getOutput.append(line);
}
br.close();
str=line;
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
protected void OnPostExecute(String otpt)
{
gm_lst.setText(otpt);
}
}.execute();
gm_lst.setText(str);
}
And then a separate issue is that you assign str = line; and only get what the last br.readLine() returned when you probably want the contents of the getOutput.
a real amateur developer here in dire need of some assistance. I've been trying to parse JSON data and turn it into a list of items, but I am having difficulties attempting to use the setListAdapter method despite importing it into the class. Any help would be massively appreciated.
Here is my main activity, error is in the onPostExecute method
import java.io.IOException;
import java.util.List;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import android.app.Activity;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
public class JSON extends Activity {
// Coordinates used for centering the Map
private final static String UNAME = "aporter";
private final static String URL = "http://api.geonames.org/earthquakesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&username="
+ UNAME;
public static final String TAG = "MapsEarthquakeMapActivity";
// Set up UI and get earthquake data
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new HttpGetTask().execute(URL);
}
private class HttpGetTask extends
AsyncTask<String, Void, List<GeonameRec>> {
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected List<GeonameRec> doInBackground(String... params) {
HttpGet request = new HttpGet(params[0]);
JSONResponseHandler responseHandler = new JSONResponseHandler();
try {
// Get Earthquake data in JSON format
// Parse data into a list of EarthQuakeRecs
return mClient.execute(request, responseHandler);
} catch (ClientProtocolException e) {
Log.i(TAG, "ClientProtocolException");
} catch (IOException e) {
Log.i(TAG, "IOException");
}
return null;
}
#Override
protected void onPostExecute(List<GeonameRec> result) {
if (null != mClient)
mClient.close();
setListAdapter(new ArrayAdapter<String>(
JSON.this,
R.layout.listitem, result));
}
}
}
}
And here is my class where I format the JSON response.
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.impl.client.BasicResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
public class JSONResponseHandler implements
ResponseHandler<List<GeonameRec>> {
#Override
public List<GeonameRec> handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
List<GeonameRec> result = new ArrayList<GeonameRec>();
String JSONResponse = new BasicResponseHandler()
.handleResponse(response);
try {
JSONObject object = (JSONObject) new JSONTokener(JSONResponse)
.nextValue();
JSONArray earthquakes = object.getJSONArray("earthquakes");
for (int i = 0; i < earthquakes.length(); i++) {
JSONObject tmp = (JSONObject) earthquakes.get(i);
result.add(new GeonameRec(
tmp.getDouble("lat"),
tmp.getDouble("lng")));
}
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
}
setListAdapter method is available in ListActivity not in Activity.
to do so in an Activity sub class, you should define your ListView and call listView.setAdapter
I have to retrieve json object from json file from this url.
My code is throwing java.lang.RuntimeException in doInBackground() and string to jsonObject conversion exception.
Can anyone help me at this? I am new to Android programming.
package course.examples.networkingearthquake;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.AsyncTask;
import android.widget.Button;
import android.view.View;
import android.widget.TextView;
import android.widget.EditText;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;
import android.net.http.AndroidHttpClient;
public class HttpActivity extends ActionBarActivity {
TextView mTextView;
EditText etInput;
TextView input;
String number;//edited
int num;//edited
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_socket);
mTextView = (TextView)findViewById(R.id.text1);
input = (TextView)findViewById(R.id.input);
etInput = (EditText)findViewById(R.id.etInput);
input.setText("Input");
//number = etInput.getText().toS();
final Button btDisplay = (Button)findViewById(R.id.btDisplay);
btDisplay.setText("DISPLAY");
btDisplay.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
new HttpGetTask().execute();
}
});
}
private class HttpGetTask extends AsyncTask<Void, Void, String>{
private static final String TAG = "HttpGetTask";
private static final String URL = "http://earthquake.usgs.gov/earthquakes/feed/geojsonp/2.5/week";
AndroidHttpClient mClient = AndroidHttpClient.newInstance("");
#Override
protected String doInBackground(Void... params){
HttpGet request = new HttpGet(URL);
JSONResponseHandler responseHandler = new JSONResponseHandler();
// ResponseHandler<String> responseHandler = new BasicResponseHandler();
try{
return mClient.execute(request,responseHandler);
}catch(ClientProtocolException exception){
exception.printStackTrace();
}catch(IOException exception){
exception.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result){
if(null != mClient)
mClient.close();
mTextView.setText(result);
}
}
private class JSONResponseHandler implements ResponseHandler<String>{
#Override
public String handleResponse(HttpResponse response)
throws ClientProtocolException, IOException {
String result = null;
String JSONResponse = new BasicResponseHandler().handleResponse(response);
JSONResponse = JSONResponse.substring(17, JSONResponse.length()-3);
num = Integer.parseInt(number);// edited
try {
JSONObject responseObject = (JSONObject) new JSONTokener(
JSONResponse).nextValue();
JSONArray features = responseObject.getJSONArray("features");
JSONObject retObject = (JSONObject)features.get(num);//edited
// JSONObject geometry = (JSONObject)retObject.get("geometry");
result = retObject.toString();
} catch (JSONException e) {
e.printStackTrace();
}
return result;
}
}
The JSON returned by the URL you specify containts eqfeed_callback() which needs to be stripped in order to make it valid JSON.
It seems like you have done this in your response handler, but you are cutting off one character too much at both the start and the end.
Try this:
JSONResponse = JSONResponse.substring(16, JSONResponse.length()-2);