I am working on an android app that is supposed to send gps locations to mysql database using php.
I have the Set_Location class which gets the gps location of a user upon the click of a button and the BackgroundLocation class which is supposed to send these coordinates to the mysql database. I have a problem passing these values. I am using context on the BackgroundLocation class and passing the values as parameters. Here is my Set_Location class:
package com.example.bensonkorir.m_ulinzi;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.provider.Settings;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Set_Location extends AppCompatActivity implements LocationListener {
private Button button;
private TextView textView,latitude,longitude;
private LocationListener locationListener;
private LocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set__location);
button = (Button) findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);
latitude = (TextView) findViewById(R.id.lat);
longitude = (TextView) findViewById(R.id.lon);
locationManager=(LocationManager)getSystemService(LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double lat= location.getLatitude();
double lon= location.getLongitude();
String type="location";
latitude.setText(Double.toString(lat));
longitude.setText(Double.toString(lon));
String lat2 = String.valueOf(location.getLatitude());
String lon2= String.valueOf(location.getLongitude());
BackgroundLocation backgroundLocation = new BackgroundLocation(this);
backgroundLocation.execute(type, lat2,lon2);
textView.append("\n"+location.getLatitude()+","+location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
ConfigureButton();
}
private void ConfigureButton() {
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
locationManager.requestLocationUpdates("gps",5000,0,locationListener);
}
});
}
}
and this is my BackgroundLocation Class:
package com.example.bensonkorir.m_ulinzi;
import android.app.AlertDialog;
import android.content.Context;
import android.location.LocationListener;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundLocation extends AsyncTask<String, Void, String> {
LocationListener locationListener;
AlertDialog alertDialog;
BackgroundLocation (LocationListener locationListener){ this.locationListener= locationListener;}
#Override
protected String doInBackground(String... params) {
String Register_Url= "http://192.168.43.254/register2.php";
String type = params[0];
if(type.equals("location")){
try {
String langitude=params[1];
String longitude=params[2];
URL url= new URL(Register_Url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data= URLEncoder.encode("username", "UTF-8")+"="+URLEncoder.encode(String.valueOf(langitude),"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(String.valueOf(longitude),"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line;
while ((line=bufferedReader.readLine())!=null){
result += line;
}
bufferedReader.close();;
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog= new AlertDialog.Builder((Context) locationListener).create();
alertDialog.setTitle(" Status");
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
}
}
Kindly assist me with this or point me in the right direction, thanks.
Related
I have this class WelcomeActivity and backgroundLogin which does a login sequence. I have my username and password editbox on the WelcomeActivity and then the login button is pressed I proceeds to the backgroungLogin to connect to the database and then compare the values of the available entries.
WelcomeActivity:
package com.a000webhostapp.cbhtermitecontrol.termitecontrol;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class WelcomeActivity extends AppCompatActivity{
Button loginButton;
EditText userText, codeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
loginButton = (Button) findViewById(R.id.loginButtonXML);
userText = (EditText) findViewById(R.id.userTextXML);
codeText = (EditText) findViewById(R.id.codeTextXML);
loginButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = userText.getText().toString();
String password = codeText.getText().toString();
String type = "login";
backgroundLogin backgroundLogin = new backgroundLogin(WelcomeActivity.this);
backgroundLogin.execute(type, username, password);
}
});
}
public void onLogin(View view){
String username = userText.getText().toString();
String password = codeText.getText().toString();
String type = "login";
backgroundLogin backgroundLogin = new backgroundLogin(this);
backgroundLogin.execute(type, username, password);
}
}
backgroundActivity:
package com.a000webhostapp.cbhtermitecontrol.termitecontrol;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.speech.tts.Voice;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class backgroundLogin extends AsyncTask<String, Void, String> {
Context context;
AlertDialog alertDialog;
backgroundLogin (Context ctx){
this.context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "https://cbhtermitecontrol.000webhostapp.com/android/loginA2DB.php";
if(type.equals("login"))
try {
String username = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("username", "UTF-8")+"="+URLEncoder.encode(username, "UTF-8")+"&"
+URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line;
while ((line = bufferedReader.readLine())!=null){
result+=line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
There are my code, however when I pressed the login button the onPre/PostExecute seem not working. Looking in the Run App Logs in Android Studio the only feed back I got after pressing the login button is this
D/libc: [NET] android_getaddrinfo_proxy get netid:0
D/libc: [NET] android_getaddrinfo_proxy-, success
Make sure to call
alertDialog.show();
In both onPreExecute and onPostExecute
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");
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'
I'm trying to get strings from my Arduino with my Android phone, everything goes well except for when I press my updatebutton the second time, it unfortunately stops.
I can't seem to track the problem and I ran out of options so I'm asking for help to you guys now.
package com.TRY.udp2;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private String rcvStr, serverIP="192.168.0.15";
private TextView textLog;//Log for outputs
private EditText textMsg;
Button updateButton;//(dis)connect Button
Boolean connected=false;//stores the connectionstatus
DataOutputStream dataOutputStream = null;//outputstream to send commands
Socket socket = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button updateButton = (Button) findViewById(R.id.updateButton);
textMsg = (EditText) findViewById(R.id.textMsg);
textLog = (TextView) findViewById(R.id.textLog);
updateButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String textlogMsg = textMsg.getText().toString();
new synchTask().execute(textlogMsg);
}
});
}
private class synchTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String msg=params[0].toString();
InetAddress toAddress = null;
try
{
toAddress = InetAddress.getByName(serverIP);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
int port=5000;
DatagramSocket dtSocket = null;
try
{
dtSocket = new DatagramSocket(port);
}
catch (SocketException e1)
{
e1.printStackTrace();
}
byte[] dataBytes = msg.getBytes();
DatagramPacket sndPacket = new DatagramPacket(dataBytes, dataBytes.length, toAddress, port);
try
{
dtSocket.send(sndPacket);
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
byte[] rcvData = new byte[1024];
DatagramPacket rcvPacket = new DatagramPacket(rcvData, rcvData.length);
dtSocket.receive(rcvPacket);
rcvStr = new String(rcvPacket.getData());
}
catch (IOException e)
{
e.printStackTrace();
}
return rcvStr;
}
protected void onPostExecute(String result) {
textLog.setText(rcvStr);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
and if there's a better way of getting strings from arduino please help out.
You probably need to close dtSocket at the end of doInBackground(). Otherwise you will try to create a socket on a bound port when you execute it the second time.
I want to get the latitude and longitude positions from the Geo Coding API. I wrote the following code for that.
package com.appulento.mapsexample.pack;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;
import com.mapsinfo.pack.DBAdapter;
public class MapsMianClass extends MapActivity {
private MapController mapController;
private LocationManager locationManager;
private MapView mapView;
List<Overlay> listOfOverlays ;
private List mapOverlays;
private Projection projection;
private Geocoder geoCoder;
private MapController mc;
private GeoPoint gP;
private DBAdapter db;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//here i am giving the Maps Geo coding API URL
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true_or_false"));
startActivity(intent);
//starting the Intent
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
//default method of maps Activity.
}
}
Is it correct? How can I incorporate JSON in the above code for getting latitude and longitude values from the URL?
Try this Code
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
AsyncTask<String, Void, Void> stringVoidVoidAsyncTask = new AsyncTask<String, Void, Void>() {
BufferedReader in;
#Override
protected Void doInBackground(String... strings) {
String url = "";
if (strings.length > 0) {
url = strings[0];
} else {
return null;
}
try {
HttpClient httpClient = new DefaultHttpClient();// Client
HttpGet getRequest = new HttpGet();
getRequest.setURI(new URI(url));
HttpResponse response = httpClient.execute(getRequest);
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
JSONObject jsonObject = new JSONObject(page);
JSONArray jsonArray = (JSONArray) jsonObject.get("results");
if (jsonArray.length() > 0) {
jsonObject = (JSONObject) jsonArray.get(0);
jsonObject = (JSONObject) jsonObject.get("geometry");
JSONObject location = (JSONObject) jsonObject.get("location");
Double lat = (Double) location.get("lat");
Double lng = (Double) location.get("lng");
System.out.println("lat - " + lat + " , lon - " + lng);
}
System.out.println(page);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
};
stringVoidVoidAsyncTask.execute("http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true");
}
}
And do add permission in AndroidManifest for Internet
<uses-permission android:name="android.permission.INTERNET"/>
And for next time do homework before asking question do googleing first. Hope this help you.
What are you want to start in StartActivity() method in Activity's onCreate()?
You should go for http request using HttpClient
and parse the response from it