I want to read a data from MYSQL database via PHP, JSON from Android.
I've been trying many different examples, but my Android phone wasn't able to read any data.
When I run the application my phone doesn't do anything after loading the application :(
MYSQL db info
Data Base Name : PeopleData
Table Name : people
Table has : id, name, sex, birthyear
PHP source : I tested index.php, and the result was correct.
-index.php
<?php
mysql_connect("127.0.0.1","root","");
mysql_select_db("PeopleData");
$q=mysql_query("SELECT * FROM people WHERE birthyear>1980");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close();
?>
Android java file for fetching database
package com.json;
import java.io.IOException;
import org.apache.http.HttpEntity;
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 org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class JSON extends Activity {
TextView resultView;
HttpClient client;
JSONObject json;
// the year data to send
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.json);
resultView = (TextView) findViewById(R.id.tvjson);
client = new DefaultHttpClient();
new Read().execute("text");
}
public JSONObject RedData() throws ClientProtocolException,IOException,JSONException {
HttpPost httppost = new HttpPost("http://127.0.0.1/series/database/index.php");
HttpResponse r = client.execute(httppost);
int status = r.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray jArray = new JSONArray(data);
JSONObject last = jArray.getJSONObject(0); // 0 -> the last object
return last;
} else {
Toast.makeText(JSON.this, "error", Toast.LENGTH_LONG);
return null;
}
}
public class Read extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
json = RedData();
return json.getString(arg0[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String data) {
// TODO Auto-generated method stub
resultView.setText(data);
}
}
}
xml
<TextView
android:id="#+id/tvjson"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TextView>
manifest
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".JSON"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Console
[2012-02-22 16:19:58 - json] Android Launch!
[2012-02-22 16:19:58 - json] adb is running normally.
[2012-02-22 16:19:58 - json] Performing com.json.JSON activity launch
[2012-02-22 16:19:58 - json] Automatic Target Mode: Unable to detect device compatibility. Please select a target device.
[2012-02-22 16:19:59 - json] Uploading json.apk onto device '01499EF80D00D009'
[2012-02-22 16:19:59 - json] Installing json.apk...
[2012-02-22 16:20:01 - json] Success!
[2012-02-22 16:20:01 - json] Starting activity com.json.JSON on device 01499EF80D00D009
[2012-02-22 16:20:02 - json] ActivityManager: Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.json/.JSON }
device
doing nothing
I don't know what I can do anymore. Please anybody help me.
Thank you.
This should work
package com.Online.Test;
import java.io.IOException;
import org.apache.http.HttpEntity;
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 org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class OnlineTestActivity extends Activity {
/** Called when the activity is first created. */
TextView resultView;
HttpClient client;
JSONObject json;
String Dat;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
resultView = (TextView) findViewById(R.id.tvjson);
client = new DefaultHttpClient();
try {
json = RedData();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Dat = json.toString();
new Read().onPostExecute(Dat);
}
public JSONObject RedData() throws ClientProtocolException, IOException, JSONException {
HttpPost httppost = new HttpPost("//link.php");
HttpResponse r = client.execute(httppost);
// int status = r.getStatusLine().getStatusCode();
//if (status == 200) {
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray jArray = new JSONArray(data);
JSONObject last = jArray.getJSONObject(0); // 0 -> the last object
return last;
// } else {
// Toast.makeText(OnlineTestActivity.this, "error", Toast.LENGTH_LONG);
// return null;
//}
}
public class Read extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try {
json = RedData();
//Toast.makeText(OnlineTestActivity.this, json.getString(arg0[0]), Toast.LENGTH_LONG);
return json.getString(arg0[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String data) {
// TODO Auto-generated method stub
resultView.setText(data);
}
}
}
Have a look to the points
The IP address 127.0.0.1 refers to the local device, so for one the
HTTP request is not leaving the device/emulator.
At your Server Side Script (here PHP), set
header('content-type:application/json;charset=utf-8');
At doInBackground's Try block, check whether your ReadData() null or
not.
At JSONArray jArray = new JSONArray(data); check whether jArray null
or not
The following tutorials may help you
http://www.codeproject.com/Articles/267023/Send-and-receive-json-between-android-and-php
http://appinventor.blogspot.com/2011/09/android-mysql-connectivity-via-json.html
Cannot parse JSON data from MySQL Database
Make sure your computer is tethered in the same network as your phone.
replace 127.0.0.1 with the ipaddress of your computer,, to get the ip address of your computer, perform a :
"ipconfig" in windows cmd as admin or "ifconfig" on linux, idk for mac
then run your app, this should worj....if still you dont get any data, replace your code, and specifically here:
Dont use JSONArray, instead pass all the data from EnyityUtils to a String and later to a JSONObject without passing via a JSONArray
Make sure your computer is tethered in the same network as your phone.
replace 127.0.0.1 with the ipaddress of your computer,, to get the ip address of your computer, perform a :
"ipconfig" in windows cmd as admin or "ifconfig" on linux, idk for mac
then run your app, this should worry you..if still you dont get any data, replace your code, and specifically here:
Dont use JSONArray, instead pass all the data from EnyityUtils to a String and later to a JSONObject without passing via a JSONArray
Related
An error occurs when searching for a city using the Android application. After I type a city, state, country (for example: New York, New York, US) and press the search button, the app crashes and gives me a NullPointerException.
MainActivity.java
package com.xxxx.weatherviewer;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ListView;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
// List of Weather objects representing the forecast
private List<Weather> weatherList = new ArrayList<>();
// ArrayAdapter for binding Weather objects to a ListView
private WeatherArrayAdapter weatherArrayAdapter;
private ListView weatherListView; // displays weather info
// configure Toolbar, ListView and FAB
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// autogenerated code to inflate layout and configure Toolbar
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// create ArrayAdapter to bind weatherList to the weatherListView
weatherListView = findViewById(R.id.weatherListView);
weatherArrayAdapter = new WeatherArrayAdapter(this, weatherList);
weatherListView.setAdapter(weatherArrayAdapter);
// configure FAB to hide keyboard and initiate web service request
FloatingActionButton fab =
findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// get text from locationEditText and create web service URL
EditText locationEditText =
findViewById(R.id.locationEditText);
URL url = createURL(locationEditText.getText().toString());
// hide keyboard and initiate a GetWeatherTask to download
// weather data from OpenWeatherMap.org in a separate thread
if (url != null) {
dismissKeyboard(locationEditText);
GetWeatherTask getLocalWeatherTask = new GetWeatherTask();
getLocalWeatherTask.execute(url);
}
else {
Snackbar.make(findViewById(R.id.coordinatorLayout),
R.string.invalid_url, Snackbar.LENGTH_LONG).show();
}
}
});
}
// programmatically dismiss keyboard when user touches FAB
private void dismissKeyboard(View view) {
InputMethodManager imm = (InputMethodManager) getSystemService(
Context.INPUT_METHOD_SERVICE);
assert imm != null;
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
// create openweathermap.org web service URL using city
private URL createURL(String city) {
String apiKey = getString(R.string.api_key);
String baseUrl = getString(R.string.web_service_url);
try {
// create URL for specified city and imperial units (Fahrenheit)
String urlString = baseUrl + URLEncoder.encode(city, "UTF-8") +
"&units=imperial&cnt=16&APPID=" + apiKey;
return new URL(urlString);
}
catch (Exception e) {
e.printStackTrace();
}
return null; // URL was malformed
}
// makes the REST web service call to get weather data and
// saves the data to a local HTML file
private class GetWeatherTask extends AsyncTask<URL, Void, JSONObject> {
#Override
protected JSONObject doInBackground(URL... params) {
HttpURLConnection connection = null;
try {
connection = (HttpURLConnection) params[0].openConnection();
int response = connection.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
StringBuilder builder = new StringBuilder();
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
}
catch (IOException e) {
Snackbar.make(findViewById(R.id.coordinatorLayout),
R.string.read_error, Snackbar.LENGTH_LONG).show();
e.printStackTrace();
}
return new JSONObject(builder.toString());
}
else {
Snackbar.make(findViewById(R.id.coordinatorLayout),
R.string.connect_error, Snackbar.LENGTH_LONG).show();
}
}
catch (Exception e) {
Snackbar.make(findViewById(R.id.coordinatorLayout),
R.string.connect_error, Snackbar.LENGTH_LONG).show();
e.printStackTrace();
}
finally {
assert connection != null;
connection.disconnect(); // close the HttpURLConnection
}
return null;
}
// process JSON response and update ListView
#Override
protected void onPostExecute(JSONObject weather) {
convertJSONtoArrayList(weather); // repopulate weatherList
weatherArrayAdapter.notifyDataSetChanged(); // rebind to ListView
weatherListView.smoothScrollToPosition(0); // scroll to top
}
}
// create Weather objects from JSONObject containing the forecast
private void convertJSONtoArrayList(JSONObject forecast) {
weatherList.clear(); // clear old weather data
try {
// get forecast's "list" JSONArray
JSONArray list = forecast.getJSONArray("list");
// convert each element of list to a Weather object
for (int i = 0; i < list.length(); ++i) {
JSONObject day = list.getJSONObject(i); // get one day's data
// get the day's temperatures ("temp") JSONObject
JSONObject temperatures = day.getJSONObject("temp");
// get day's "weather" JSONObject for the description and icon
JSONObject weather =
day.getJSONArray("weather").getJSONObject(0);
// add new Weather object to weatherList
weatherList.add(new Weather(
day.getLong("dt"), // date/time timestamp
temperatures.getDouble("min"), // minimum temperature
temperatures.getDouble("max"), // maximum temperature
day.getDouble("humidity"), // percent humidity
weather.getString("description"), // weather conditions
weather.getString("icon"))); // icon name
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}
This is the error message from the stacktrace:
java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONArray org.json.JSONObject.getJSONArray(java.lang.String)' on a null object reference
at com.xxxx.weatherviewer.MainActivity.convertJSONtoArrayList(MainActivity.java:171)
at com.xxxx.weatherviewer.MainActivity.access$300(MainActivity.java:30)
at com.xxxx.weatherviewer.MainActivity$GetWeatherTask.onPostExecute(MainActivity.java:157)
at com.xxxx.weatherviewer.MainActivity$GetWeatherTask.onPostExecute(MainActivity.java:106)
at android.os.AsyncTask.finish(AsyncTask.java:755)
at android.os.AsyncTask.access$900(AsyncTask.java:192)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:772)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
I believe there might be an issue with the line listed below:
JSONArray list = forecast.getJSONArray("list");
However, I am unsure of how to start....can someone please help me?
A simple fix could be to turn your catch block from:
catch (JSONException e) {
e.printStackTrace();
}
into:
catch (Exception e) {
e.printStackTrace();
}
This catches your NPE, but do note that, if you have an API for this the "list" value could be empty or having a null value in that case you can always have a checker before doing the operation on JSONArray list variable. So for example before doing this:
JSONObject day = list.getJSONObject(i);
you can surround it with:
if(forecast.has("list")) {
JSONObject day = list.getJSONObject(i);
// Same goes for day etc...
}
This ensures that it should check if the object exists in the first place before processing it to avoid NPE.
I have to get some data from a MySQL database on server. I have the following code.but the app crashes when I run it. I also get the Permission denied (missing INTERNET permission?) in my Logcat even though I specified the internet permission in my Android Manifest.
Any idea what might be wrong here?
Java file
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity {
TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
connect();
}
private void connect() {
String data;
List<String> r = new ArrayList<String>();
ArrayAdapter<String>adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,r);
ListView list=(ListView)findViewById(R.id.listView1);
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("http://xxxxx/data.php");
HttpResponse response = client.execute(request);
HttpEntity entity=response.getEntity();
data=EntityUtils.toString(entity);
Log.e("STRING", data);
try {
JSONArray json=new JSONArray(data);
for(int i=0;i<json.length(); i++)
{
JSONObject obj=json.getJSONObject(i);
String name=obj.getString("name");
String desc=obj.getString("description");
// String lat=obj.getString("lat");
Log.e("STRING", name);
r.add(name);
r.add(desc);
// r.add(lat);
list.setAdapter(adapter);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClientProtocolException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
} catch (IOException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.diana.menu" >
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<uses-permission android:name="android.permission.INTERNET"/>
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
data.php
<?php
$conn=mysql_connect('localhost', 'xxxx', 'xxxxx','u199776286_pois');
if(!$conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT name, description FROM pois';
mysql_select_db('u199776286_pois');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
echo "NAME : {$row['name']} <br> ".
"DESCRIPTION : {$row['description']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
my logcat
This happens because you're connecting to your MySQL server from the main UI thread. create a secondary thread (or async task) to connect and to get the results.
Use Async Task to get the data from your database..
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Writing the above code is not at all a better way to get rid from NetworkOnMainThreadException . You have to use any background thread for doing network operation in android above api 11 such as Asynch Task , Intent Service etc.
How to fix android.os.NetworkOnMainThreadException?
You can also use Executors for network task's
Executors.newSingleThreadExecutor().submit(new Runnable() {
#Override
public void run() {
//You can performed your task here.
}
});
Add Internet Permission in your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
Use Asynck Task like
List<String> r = new ArrayList<String>();
Need to declare out of connect();
with Oncreate
new LongOperation().execute("");
now create
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
connect();
return "Executed";
}
#Override
protected void onPostExecute(String result) {
ArrayAdapter<String>adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,r);
ListView list=(ListView)findViewById(R.id.listView1);
list.setAdapter(adapter);
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
// need to remove Ui control from connect(); and that require value
bind it on onPostExecute
use Async. For more help check this
I am writing an Android Application which has a broadcast receiver secured with permissions. The broadcast receiver on receiving requests from authenticated application scans port 80 of a hardcoded IP address. It returns the result of the socket connection attempt. In my code I have the socket connection called from OnReceive ( ) method. I am able to get to the receiver as i can see the toast messages. However, socket connection is caught by Exception E. Here is my code for the receiver :
package com.example.naveenbreceive;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.os.Bundle;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;
public class breceiver extends Activity {
BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String Target="107.20.112.24";
int i=80;
int timeout=1000;
Toast.makeText(getApplicationContext(),"Intent Received",Toast.LENGTH_LONG).show();
Log.i("INFO","toast launched");
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress(Target, i), timeout);
if (socket.isConnected())
{Toast.makeText(getApplicationContext(), "Connected to port 80", Toast.LENGTH_LONG).show();
socket.close();
}
else
{Toast.makeText(getApplicationContext(), "Unable to Connect port 80", Toast.LENGTH_LONG).show();
socket.close();
}
}
catch (UnknownHostException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),"UnknownHost Exception",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),"IO Exception",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(),"Exception",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO Auto-generated method stub
IntentFilter filterView = new IntentFilter();
filterView.addAction("com.example.HACKING");
registerReceiver(mReceiver, filterView,"com.example.permission.naveen", null);
Toast.makeText(getApplicationContext(),"Inside Receiver",Toast.LENGTH_LONG).show();
}
The broadcast receiver is on the UI thread. You can't do networking on the UI thread. You need to do it in a Thread or AsyncTask.
Also, BroadcastReceivers are supposed to be very quick and do very little work. Their design is supposed to be a quick notification and then you do the heavy lifting elsewhere, so the next app can get the notification. Networking IO is way too much work for a receiver.
I am trying to do a very simple POST from an android application to a php script that will update a database. Unfortunately, this is giving me a debugger error (eclipse) on line 52. Below is the code:
package com.example.testhttppost;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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;
}
public void updateDiscountTable(View view)
{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.test.com/jsonpost.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("shop", "ZARA"));
nameValuePairs.add(new BasicNameValuePair("discount", "20%"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost); //Line 52
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
and the PHP script is:
<?php
// PHP variable to store the host address
$db_host = "localhost";
// PHP variable to store the username
$db_uid = "dsdsdsv_android";
// PHP variable to store the password
$db_pass = "test1234";
// PHP variable to store the Database name
$db_name = "dsdsdsv_android";
// PHP variable to store the result of the PHP function 'mysql_connect()' which establishes the PHP & MySQL connection
$db_con = mysql_connect($db_host,$db_uid,$db_pass) or die('could not connect');
mysql_select_db($db_name);
$shopId = $_POST['id'];
$shopName = $_POST['shop'];
$discount = $_POST['discount'];
mysql_query("insert into discounts(id, shop, discount) values ($shopId, $shopName, $discount)");
// mysql_query("insert into discounts(id, shop, discount)values(121, 'sadsdas','dasdasdsa')");
?>
The interface of the application is nothing but a button. This button is linked with the method above defined updateDiscountTable. Thanks and looking forward to replies.
You are performing networking operations on the main application thread probably. You need to move this to a background thread. You can use Asynctask.
You need to Keep your app responsive.
I am developing an application in which first I have to search available Bluetooth devices and make connection. I have done this task. After this, one new Activity opens in which there is one Edittext and one Button. I have developed the below code. It is not giving any output.
I am passing data using MAC address of connected device.
java file...
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
#SuppressLint("NewApi")
public class NewMessage extends Activity {
Button btn;
EditText et;
String message1="Hello";//on button click by default
BluetoothAdapter mBluetoothAdapter1 = null;;
// BluetoothAdapter mBluetoothAdapter;
public static String MacAddress;
#Override
public void onCreate(Bundle mSavedInstanceState) {
super.onCreate(mSavedInstanceState);
setContentView(R.layout.message);
btn = (Button) findViewById(R.id.btn);
et = (EditText) findViewById(R.id.et);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mBluetoothAdapter1 = BluetoothAdapter.getDefaultAdapter();
byte[] toSend=message1.getBytes();
try
{
final UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothDevice device=mBluetoothAdapter1.getRemoteDevice(MacAddress);
BluetoothSocket socket=device.createInsecureRfcommSocketToServiceRecord(applicationUUID);
OutputStream mmout=socket.getOutputStream();
mmout.write(toSend);
mmout.flush();
mmout.close();
socket.close();
Toast.makeText(getBaseContext(), MacAddress, 10000).show();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
/*private void sendDataToPairedDevice(String message ,BluetoothDevice device){
byte[] toSend = message.getBytes();
try
{
BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(applicationUUID);
OutputStream mmOutStream = socket.getOutputStream();
mmOutStream.write(toSend);
// Your Data is sent to BT connected paired device ENJOY.
} catch (IOException e) {
e.printStackTrace();
}
}*/
}
xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="#string/hint">
<requestFocus />
</EditText>
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/send" />
</LinearLayout>
Please do help me...
Here is my code, which has the problem..
public void onClick(View v) {
// TODO Auto-generated method stub
mBluetoothAdapter1 = BluetoothAdapter.getDefaultAdapter();
byte[] toSend=message1.getBytes();
try
{
final UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothDevice device=mBluetoothAdapter1.getRemoteDevice(MacAddress);
BluetoothSocket socket=device.createInsecureRfcommSocketToServiceRecord(applicationUUID);
OutputStream mmout=socket.getOutputStream();
mmout.write(toSend);
mmout.flush();
mmout.close();
socket.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
This doesn't answer your question directly but one thing I am noticing is that you have 10000 as your duration parameter for Toast.makeText(), which is invalid. It only accepts Toast.LENGTH_SHORT or Toast.LENGTH_LONG, which are actually just 0 or 1. Check the docs: http://developer.android.com/reference/android/widget/Toast.html
[EDIT]
Another error I see in your code is you pass an empty String to getRemoteDevice. Try doing getRemoteDevice("00001101-0000-1000-8000-00805F9B34FB") and see what happens. Again, read the docs: http://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html#getRemoteDevice(java.lang.String)
Include the connect function.
BluetoothSocket socket=device.createInsecureRfcommSocketToServiceRecord(applicationUUID);
socket.connect(); // here
OutputStream mmout=socket.getOutputStream();