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.
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 trying to run a simple app that extracts html from a page and displays it in the logs.
Here is the Java code:
package com.example.khkr.jsondemo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public class DownloadTask extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... params) {
URL url;
String result = "";
try {
url = new URL(params[0]);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.connect();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data!=-1)
{
char current = (char)data; result+=current;
data = reader.read();
}
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather content",weatherInfo);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
The problem is I don't see any errors in the code , but when I try to run the app, I get the following Logs which never make sense to me. Here are the logs:
https://gist.github.com/khkr/d96396ff6f8e34b3e9a430a805b735a7
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);
}
I am trying to make a simple GET request to my local NodeJS server to get some JSON objects. I changed the request so it happens as an AsyncTask rather than in the UI thread. But I am still not able to get it to work. Does this code look correct? Sorry, not great with Java yet.
package com.dd.relay;
import com.dd.relay.HttpRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
public final static String EXTRA_MESSAGE = "com.dd.relay.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// We'll define a custom screen layout here (the one shown above), but
// typically, you could just use the standard ListActivity layout.
setContentView(R.layout.activity_main);
// Make a GET request for data
String url = "http://localhost.com/contacts";
String res = null;
try {
HttpRequest request = new HttpRequest();
request.execute(new URL(url));
Log.v(EXTRA_MESSAGE, res);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TextView textView = (TextView) findViewById(R.id.textv);
Context context = this.getApplicationContext();
Toast mytoast = Toast.makeText(context, res, Toast.LENGTH_LONG);
mytoast.show();
textView.setText(res);
// Create list for contacts
/* List<Map<String, RelayContact>> data = null;
// Now create a new list adapter bound to the cursor.
// SimpleListAdapter is designed for binding to a Cursor.
ListAdapter adapter = new SimpleAdapter(this, data, 0, new String[] {"First", "Number"}, new int[] {android.R.id.text1, android.R.id.text2}); // Parallel array of which template objects to bind to those columns.
// Bind to our new adapter.
this.setListAdapter(adapter);*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
And here is my custom HttpRequest AsyncTask class
package com.dd.relay;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.os.AsyncTask;
public class HttpRequest extends AsyncTask<URL, Void, Void> {
protected String doInBackground(URL url) throws Exception {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}
// Buffer the result into a string
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}
protected void onProgressUpdate(Integer progress) {
}
protected void onPostExecute(String result) {
System.out.println(result);
}
#Override
protected Void doInBackground(URL... arg0) {
// TODO Auto-generated method stub
return null;
}
}
Android does not allow network communication to be done on the UI thread. Android provides a class called AsyncTask that is intended for such interactions. See this link for details and one option for a solution (This is probably what you want):
How to fix android.os.NetworkOnMainThreadException?
or you can also create a custom class that extends Thread or implements Runnable that posts to the UI thread using a Handler
try this link hope use full to you :-
Verifying login details via http get : Android
public class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
// call function
login(userName, password);
return null;
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}