I am new to android. I am learning android networking now. I am trying to create a connection with HttpURLConnection to track the response code as 200,
but I am getting IllegalArgumentException. I am doing this with Async task but couldn't rectify. Any help would be appreciated.
Here is my code :
package com.movies.usman.moviesmesh;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new CheckConnectionStatus().execute("http://google.com");
}
class CheckConnectionStatus extends AsyncTask<String, Void, String>
{
#Override
protected String doInBackground(String... params) {
URL url = null;
try {
url = new URL(params[0]);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//Log.i("Reponse: ", String.valueOf(urlConnection.getResponseCode()));
return String.valueOf(urlConnection.getResponseCode());
} catch (IOException e) {
Log.e("Error: ", e.getMessage(), e);
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
text.setText(s);
}
}
}
You should initialize your TextView in onCreate
text = (TextView) findViewById(R.id.yourViewId);
before of
new CheckConnectionStatus().execute("http://google.com");
Related
i am trying to implement sample JSON data App that Gets JSON data from server
i am Getting complete JSON file whats wrong with my coding ?
i am following an youtube tutorial but he did successfully but i am getting complete JSON File
this is JSON server side file
{
"movies" :[
{
"movie" : "Avenger",
"year" : 2012
}
]
}
and this is code from android app
package com.yog.jsonparser;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.TextView;
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.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
TextView tvData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnHit = (Button) findViewById(R.id.btnHit);
tvData = (TextView)findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JSONTask().execute("http://myDomainName.com/getData.txt");
}
});
}
public class JSONTask extends AsyncTask<String,String,String>{
HttpURLConnection connection = null;
BufferedReader reader = null;
URI url;
StringBuffer buffer;
#Override
protected String doInBackground(String... params){
try{
//URL OF REQUESTED PAGE
url=new URI(params[0]);
connection = (HttpURLConnection) (new URL(params[0]).openConnection());
connection.connect();
InputStream stream=connection.getInputStream();
reader=new BufferedReader(new InputStreamReader(stream));
buffer=new StringBuffer();
String line;
while((line =reader.readLine())!=null){
buffer.append(line);
}
String finalJSON=buffer.toString();
JSONObject parentOject = new JSONObject(finalJSON);
JSONArray parentArray = parentOject.getJSONArray("movies");
JSONObject finalObject= parentArray.getJSONObject(0);
String movieName= finalObject.getString("movie");
int year=finalObject.getInt("year");
return movieName + "-" + year;
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if(connection !=null){
connection.disconnect();
}
try{
if(reader !=null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
tvData.setText(buffer.toString());
}
}
}
current Output :
{"movies" :[{ "movie" : "Avenger","year" : 2012}]}
Expected output :
Avenger
2012
Change your onPostExecute method as below.
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
tvData.setText(s);
}
Here s will be return statement of doInBackground. "movieName + "-" + year;"
You are getting {"movies" :[{ "movie" : "Avenger","year" : 2012}]} in the TextView because you are setting the buffer's output to the TextView. Change your onPostExecute like this:
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if(s != null){
tvData.setText(s);
}else{
//// Some error occurred
tvData.setText(buffer.toString());
}
}
i am developing a gcm chat app in android studio and i am getting this error n no idea how to resolve it. i searched about it but didn't find any thing.
Here is the code and in MainActivity.java also having same problem.
package com.example.jason.androidchat2;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.squareup.okhttp.OkHttpClient;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class ChatActivity extends Activity {
EditText editText_mail_id;
EditText editText_chat_message;
ListView listView_chat_messages;
Button button_send_chat;
List<ChatObject> chat_list;
BroadcastReceiver recieve_chat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
editText_mail_id= (EditText) findViewById(R.id.editText_mail_id);
editText_chat_message= (EditText) findViewById(R.id.editText_chat_message);
listView_chat_messages= (ListView) findViewById(R.id.listView_chat_messages);
button_send_chat= (Button) findViewById(R.id.button_send_chat);
button_send_chat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// send chat message to server
String message=editText_chat_message.getText().toString();
showChat("sent",message);
new SendMessage().execute();
editText_chat_message.setText("");
}
});
recieve_chat=new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message=intent.getStringExtra("message");
Log.d("pavan","in local braod "+message);
showChat("recieve",message);
}
};
LocalBroadcastManager.getInstance(this).registerReceiver(recieve_chat, new IntentFilter("message_recieved"));
}
private void showChat(String type, String message){
if(chat_list==null || chat_list.size()==0){
chat_list= new ArrayList<ChatObject>();
}
chat_list.add(new ChatObject(message,type));
ChatAdabter chatAdabter=new ChatAdabter(ChatActivity.this,R.layout.chat_view,chat_list);
listView_chat_messages.setAdapter(chatAdabter);
//chatAdabter.notifyDataSetChanged();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
private class SendMessage extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String url = Util.send_chat_url+"?email_id="+editText_mail_id.getText().toString()+"&message="+editText_chat_message.getText().toString();
Log.i("pavan", "url" + url);
OkHttpClient client_for_getMyFriends = new OkHttpClient();;
String response = null;
// String response=Utility.callhttpRequest(url);
try {
url = url.replace(" ", "%20");
response = callOkHttpRequest(new URL(url),
client_for_getMyFriends);
for (String subString : response.split("<script", 2)) {
response = subString;
break;
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
//Toast.makeText(context,"response "+result,Toast.LENGTH_LONG).show();
}
}
// Http request using OkHttpClient
String callOkHttpRequest(URL url, OkHttpClient tempClient)
throws IOException {
HttpURLConnection connection = tempClient.open(url);
connection.setConnectTimeout(40000);
InputStream in = null;
try {
// Read the response.
in = connection.getInputStream();
byte[] response = readFully(in);
return new String(response, "UTF-8");
} finally {
if (in != null)
in.close();
}
}
byte[] readFully(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int count; (count = in.read(buffer)) != -1;) {
out.write(buffer, 0, count);
}
return out.toByteArray();
}
}
OkHTTP is an Open Source project designed to be an efficient HTTP client.
Just add this in your build.gradle
dependencies {
compile 'com.squareup.okhttp:okhttp:2.5.0'
}
FYI
The latest release is available
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
package com.example.googlemapstestproject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends ActionBarActivity implements OnMapLongClickListener, OnMyLocationButtonClickListener,
android.view.View.OnClickListener {
private GoogleMap mMap;
Button userLocation;`enter code here`
GPSTracker gps;
PlacesTask placesTask;
ParserTask parserTask;
AutoCompleteTextView autoCompView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autoCompView = (AutoCompleteTextView) findViewById(R.id.atv_places);
autoCompView.setThreshold(1);
autoCompView.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
placesTask = new PlacesTask();
placesTask.execute(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
try {
// Loading map
initilizeMap();
} catch (Exception e) {
e.printStackTrace();
}
mMap.setOnMapLongClickListener(this);
mMap.setMyLocationEnabled(true);
mMap.getUiSettings().setZoomControlsEnabled(true);
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
Log.d("Exception while downloading url", e.toString());
}
finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
// Fetches all places from GooglePlaces AutoComplete Web Service
private class PlacesTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... place) {
// For storing data from web service
String data = "";
// Obtain browser key from https://code.google.com/apis/console
String key = "key=AIzaSyDTg7d-JNRLRxe75QDEEeAGr1xnSHGX9V4";
String input = "";
try {
input = "input=" + URLEncoder.encode(place[0], "utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// place type to be searched
String types = "types=(cities)";
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = input + "&" + types + "&" + sensor + "&" + key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/autocomplete/" + output + "?" + parameters;
try {
// Fetching the data from we service
data = downloadUrl(url);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result) {
// Instantiating ParserTask which parses the json data from
// Geocoding webservice
// in a non-ui thread
ParserTask parserTask = new ParserTask();
// Start parsing the places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
// A class to parse the Google Places in JSON format
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
JSONObject jObject;
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try {
jObject = new JSONObject(jsonData[0]);
// Getting the parsed data as a List
places = placeJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
String[] from = new String[] { "description" };
int[] to = new int[] { R.layout.listview_layout };
// Creating a SimpleAdapter for the AutoCompleteTextView
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result, android.R.layout.simple_list_item_1, from, to);
// Setting the adapter
autoCompView.setAdapter(adapter);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Updated code update, everything looks fine it is just that there is nothing appearing still when I type in a place.
I have made the google maps half and half with a listview as well so if anyone has any good solutions on how to get them to work together that would be great.
If you would like to use a library that provides a GooglePlaceAutoComplete widget, check out Sprockets (I'm the developer). After setting it up with your API key, you could add a working Places API autocomplete to your layout with something like:
<net.sf.sprockets.widget.GooglePlaceAutoComplete
xmlns:sprockets="http://schemas.android.com/apk/res-auto"
android:id="#+id/place"
android:layout_width="match_parent"
android:layout_height="wrap_content"
sprockets:types="(cities)"/>
I'm trying to connect to a servlet in localhost from my Android Emulator.
I created a project in Eclipse named SimpleHttpGetRequest with an activity named "HttpGetServletActivity".
I created in NetBeans a project named "HttpGetRequest" containing a servlet.
The code in my "HttpGetServletActivity" activity is :
package com.mobdev.simplehttprequest;
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 java.net.URLConnection;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class HttpGetServletActivity extends Activity implements OnClickListener {
Button button;
TextView outputText;
public static final String URL = "http://10.0.2.2:8080/HttpGetRequest/HelloWorldServlet";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewsById();
button.setOnClickListener(this);
}
private void findViewsById() {
button = (Button) findViewById(R.id.button);
outputText = (TextView) findViewById(R.id.outputTxt);
}
public void onClick(View view) {
GetXMLTask task = new GetXMLTask();
task.execute(new String[]{ URL });
}
private class GetXMLTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String output = null;
for (String url : urls) {
output = getOutputFromUrl(url);
}
return output;
}
private String getOutputFromUrl(String url) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = getHttpConnection(url);
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
} catch (IOException e1) {
e1.printStackTrace();
}
return output.toString();
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("get");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
#Override
protected void onPostExecute(String output) {
outputText.setText(output);
}
}
}
The source code of my servlet is :
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorldServlet extends HttpServlet {
public HelloWorldServlet() {
super();
}
#Override
protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello Android !!!!");
}
}
I deployed my servlet in Apache server (i'm using xampp);
I added permission for network connection
When I run my App and click on the button, the App crashes, and I don't know why !!
Can anybody help me, please ? Im' stuck.
I tried :
Wifi connection : I did run my App on a real device, instead of "10.0.2.2" I put the ip adress of my PC but it doesn't work ;
Access to project HttpGetrequest from Android Emulator browser, it worked ;
For some reason the onPreExecute isn't being called. Code:
protected void onPreExcecute() {
hook.createDialog(ticker);
}
Entire class:
package com.evandarwin.finance;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
public class GetTicker extends AsyncTask<String, Integer, String>{
private Context ctx;
private String ticker;
private SimpleFinanceActivity hook;
public GetTicker(Context ctx, String ticker, SimpleFinanceActivity hook) {
this.ctx = ctx;
this.ticker = ticker.toUpperCase();
this.hook = hook;
}
protected void onPreExcecute() {
hook.createDialog(ticker);
}
#SuppressWarnings("unused")
#Override
protected String doInBackground(String... params) {
try {
URL url = new URL("http://finance.yahoo.com/d/quotes.csv?s="+ticker+"&f=a");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.connect();
InputStream is = urlConnection.getInputStream();
StringBuffer str = new StringBuffer();
int bufferLength = 0; //used to store a temporary size of the buffer
byte[] stream = new byte[1024];
while ( (bufferLength = is.read(stream)) > 0 ) {
str.append(stream);
}
return str.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
hook.destroyDialog();
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
}
This is giving me a NullPointerException, I know I've had this problem before but I don't remember what I did to fix it. Please help! :P
The reason the #Override is causing a problem in Eclipse (and the reason the method isn't being called) is that you have made a typing error.
You are calling it onPreExcecute (note the 'c' after the 'x' shouldn't be there). Correct it to be onPreExecute and use #Override for that.