Android, Connecting to MySQL using PHP: Null Pointer exception - php

Im a newbie to android, I am learning to connect to a server through android client using Php, MySql and JSON. For testing purpose im running on localhost.
So for here's what I've done.
Database demo.php
public class Database_demo extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
List<String> r = new ArrayList<String>();
try{
//http post
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://10.0.2.2/PhpAndMySql/category.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
}
//Convert response to string
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch(Exception e)
{
Toast.makeText(getBaseContext(),e.toString() ,Toast.LENGTH_LONG).show();
}
//END Convert response to string
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++)
{
json_data = jArray.getJSONObject(i);
r.add(json_data.getString("category"));
}
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, r));
}
catch(JSONException e1){
Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
Toast.makeText(getBaseContext(),e1.toString() ,Toast.LENGTH_LONG).show();
}
}
}
category.php
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$q=mysql_query("SELECT * FROM category ORDER BY 'category'.'category' ASC");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
MySQL
CREATE TABLE `test`.`category` (
`category_id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`category` VARCHAR( 255 ) NOT NULL
) ENGINE = MYISAM ;
I am getting a NullPointer Exception, when I execute in android.
Is the Php File correct?
Please I need your help with this!
Thanks

I'm thinking your php should be as follows (instead of quotes on the table.column use backticks).
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
$q=mysql_query("SELECT * FROM category ORDER BY `category` ASC");
$output = array();
while($row = mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>

Related

Mobile phone Ready to connect mysql unexpectedly quit

I have use mysql for a while, and there is no problem with the connection between computers.
I’m practicing Android Studio recently.
Reference URL:https://www.youtube.com/watch?v=EZshEey2feg
I am executing on Android Studio, quite perfect, without any errors
But I packaged it into an .apk installation, execute
Immediately unexpected quit, no warning
I found that when reading mysql data, it will unexpectedly quit
My code
[MainActivity.java]
private Runnable runTimerStop = new Runnable() {
#Override
public void run() {
select(null);
}
};
public void select(String id) {
try {
String r = DBphp.DBstring(id,cookieStr,url);
JSONArray jsonArray = new JSONArray(r);
List<Map<String,Object>> items = new ArrayList<Map<String, Object>>();
for (int i = 0 ; i < jsonArray.length() ; i++){
JSONObject jsonData = jsonArray.getJSONObject(i);
Map<String,Object> item = new HashMap<String,Object>();
item.put("ID",jsonData.getString("ID"));
item.put("Name",jsonData.getString("Name"));
item.put("m1",jsonData.getString("m1"));
item.put("m2",jsonData.getString("m2"));
item.put("m3",jsonData.getString("m3"));
items.add(item);
}
SimpleAdapter SA = new SimpleAdapter(context,items,R.layout.list_text, new String[]{"ID", "Name", "m1", "m2", "m3"}, new int[]{R.id.text0, R.id.text1, R.id.text2, R.id.text3, R.id.text4});
LV1.setAdapter(SA);
} catch (Exception e) {
Log.e("log_tag", e.toString());
}
}
[DBphp.java]
public class DBphp {
private static HttpClient hC;
private static HttpPost hP;
public static String DBstring(String i, String Wcook, String url){
String result="Error";
try{
hC = new DefaultHttpClient();
hP = new HttpPost(url+"/index.php");
hP.addHeader("Cookie",Wcook+";expires=thu,31-Dec-37 23:55:55 GMT; path=/");
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("S1",i));
hP.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
HttpResponse hR = hC.execute(hP);
HttpEntity hE = hR.getEntity();
InputStream inputStream = hE.getContent();
BufferedReader bufReader = new BufferedReader(new InputStreamReader(inputStream, HTTP.UTF_8),8);
StringBuilder builder = new StringBuilder();
String line=null;
while ((line = bufReader.readLine()) != null){
builder.append(line+"\n");
}
inputStream.close();
result = builder.toString();
}catch (Exception e){
result=e.toString();
}finally {
hC.getConnectionManager().shutdown();
}
return result;
}
}
[SQL_data.php]
<?PHP
$hostname = "192.168.1.240";
$username = "AppUser";
$password = "root";
$database = "text";
$GD = mysqli_connect($hostname, $username, $password) or trigger_error(mysqli_error(), E_USER_ERROR);
//UTF8
mysqli_query($GD, "SET NAMES UTF8");
mysqli_query($GD, "SET CHARACTER_SET_CLIENT='utf8'");
mysqli_query($GD, "SET CHARACTER_SET_RESULTS='utf8'");
?>
[index.php]
<?php
require_once("SQL_data.php");
$sql="SELECT * FROM `text1` ORDER BY `ID`DESC;";
mysqli_select_db($GD,$database);
$Result=mysqli_query($GD,$sql) or die(mysqli_error($GD));
while($r = mysqli_fetch_assoc($Result))
$output[]=$r;
header('Content-type: application/json; charset=utf-8');
print(json_encode($output,JSON_UNESCAPED_UNICODE));
exit();
mysql_close();
?>
Why is this happening? Please help me.

No Error : Data is not inserting in PHP MySql from Android

Data is not inserting in MySql from android there is no error in the code, i have defined them using AsyncThread - doInBackground and onPostExecute..Its showing the toast what i have defined in Json Object Try Catch Method 'Sorry Try Again' in else condition if data is not inserted.
InputStream is = null;
String res = null;
String line = null;
int code;
onClick Code
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
question = addque.getText().toString();
choice1 = addc1.getText().toString();
choice2 = addc2.getText().toString();
choice3 = addc3.getText().toString();
answer = addanswer.getText().toString();
Explanation = addexplan.getText().toString();
AsyncTaskRunner Class
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
ArrayList<NameValuePair> nameValuePairs = new
ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("question", question));
nameValuePairs.add(new BasicNameValuePair("choice1", choice1));
nameValuePairs.add(new BasicNameValuePair("choice2", choice2));
nameValuePairs.add(new BasicNameValuePair("choice3", choice3));
nameValuePairs.add(new BasicNameValuePair("answer", answer));
nameValuePairs.add(new BasicNameValuePair("Explanation",
Explanation));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new
HttpPost("http://192.168.43.4/insert/insert.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
}
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
res = sb.toString();
Log.e("pass 2", "connection success ");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
try
{
JSONObject json_data;
json_data = new JSONObject(res);
code = json_data.getInt("code");
if(code==1)
{
Toast.makeText(getActivity(), "Inserted Successfully",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getActivity(), "Sorry, Try Again",
Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
}
PHP Code
<?php
$host='localhost';
$uname='root';
$pwd='';
$db="quizDB";
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
$question=$_REQUEST['question'];
$choice1=$_REQUEST['choice1'];
$choice2=$_REQUEST['choice2'];
$choice3=$_REQUEST['choice3'];
$answer=$_REQUEST['answer'];
$Explanation=$_REQUEST['Explanation'];
$flag['code']=0;
if($r=mysql_query("insert into quizquestion values('$question','$choice1',
$choice2, '$choice3', '$answer', '$Explanation') ",$con))
{
$flag['code']=1;
echo"hi";
}
print(json_encode($flag));
mysql_close($con);
?>
Correct me if i am wrong.
first get all string you want to insert and then call AsyncTask. may be this solve .
question = addque.getText().toString();
choice1 = addc1.getText().toString();
choice2 = addc2.getText().toString();
choice3 = addc3.getText().toString();
answer = addanswer.getText().toString();
Explanation = addexplan.getText().toString();
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
and also change this 2 line . pass UTF-8 to UrlEncodeFormEntity
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
httppost.setEntity(formEntity);
Edited
I think you forget to add concatination onto $choice2 , and change query like this. pass first fieldName and then Values.
$sql = "INSERT INTO MyGuests (fieldName1, fieldName2, fieldName3,fieldName4,fieldName5,fieldName6)
VALUES ('$question','$choice1','$choice2', '$choice3', '$answer', '$Explanation')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
$flag['code']=1;
echo"hi";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

Android cannot insert into database string with accents and blank space

I´m having a problem with this string: "Não Vou". It means "I don´t go". I´m trying to insert it into database with php/json file.
When I remove blank space and ~ accent it works fine.
What I have tried:
changed iso-8859-1 to utf-8;
changed eclipse encoding to utf-8;
changed print(json_encode($flag)) to print(json_encode('utf8_encode', $flag));
Have read similar posts but any of them helped me.
public class insertNo extends AsyncTask<String, Boolean, Boolean>{
#Override
protected Boolean doInBackground(String... params) {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("e_id", subString));
nameValuePairs.add(new BasicNameValuePair("Não Vou", no));
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://mywebsite.com/includes/insert_counter.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
inputStream = entity.getContent();
Log.e("pass 1", "connection success");
}catch(Exception e){
Log.e("Fail 1", e.toString());
Log.e("Invalid IP", e.toString());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
inputStream.close();
result = stringBuilder.toString();
Log.e("pass 2", "connection success");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
try {
JSONObject json_data = new JSONObject(result);
code = (json_data.getInt("code"));
if (code==1) {
Log.d("Insert success", result);
} else {
Log.d("Sorry son", result);
}
} catch (Exception e) {
Log.e("Fail 3", e.toString());
}
return null;
}
}
php file
include_once("db_connect.php");
$e_id = $_REQUEST["e_id"];
$yes = $_REQUEST["Vou"];
$no = $_REQUEST["Não Vou"];
$maybe = $_REQUEST["Talvez"];
$flag['code']=0;
if(isset($yes)){
$r = mysqli_query($mysqli, "UPDATE table1 SET yes = yes + 1 WHERE id='$e_id'");
$flag['code']=1;
}else if(isset($no)){
$r = mysqli_query($mysqli, "UPDATE table1 SET no = no + 1 WHERE id='$e_id'");
$flag['code']=1;
}else if(isset($maybe)){
$r = mysqli_query($mysqli, "UPDATE table1 SET maybe = maybe + 1 WHERE id='$e_id'");
$flag['code']=1;
}
print(json_encode($flag));
mysqli_close($mysqli);
From the documentation, PHP variables should not contain special characters, or spaces, or anything out of
a letter is a-z, A-Z, and the bytes from 127 through 255 (0x7f-0xff).

Save the id only of a row in the SQLite android database

My android app is getting & writing data to the server and to the SQlite database.
I am fetching values for jobaddress.id = 1from server using a query (below). The values in SELECTstatement are displaying perfectly in the UI of android app however when I press "Save", instead of values from the server, I need to save the id 1 from the server in the local database without shwoing the id in the UI.
PHP sript (query only) for retrieving data from server:
$tsql = "SELECT tbl_manufacturers.manufacturers_name, tbl_appliances_models.appliances_models_name, tbl_appliances.appliances_serial, tbl_appliances.appliances_id, jobaddress.id
FROM jobaddress INNER JOIN
tbl_appliances ON jobaddress.id = tbl_appliances.appliances_jobaddress_id LEFT OUTER JOIN
tbl_appliances_models INNER JOIN
tbl_manufacturers ON tbl_appliances_models.appliances_models_manufacturers_id = tbl_manufacturers.manufacturers_id ON
tbl_appliances.appliances_models_id = tbl_appliances_models.appliances_models_id
WHERE (tbl_appliances.appliances_companies_id = 1) AND (jobaddress.id = 1)";
Showing data using JSON Parser:
public void getJobAddress()
{
String result = null;
InputStream isr = null;
try
{
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://datanetbeta.multi-trade.co.uk/tablet/getJobAddress.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e)
{
Log.e("Log_tag", "Error in hhtp connection " + e.toString());
}
//convert Response to string
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
isr.close();
result = sb.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result " + e.toString());
}
try
{
JSONArray jArray = new JSONArray(result);
for(int i=0; i < jArray.length(); i++)
{
JSONObject json = jArray.getJSONObject(0);
s = json.getString("address1");
t = json.getString("address2");
u = json.getString("postcode");
}
tvJbAddrs1.setText(s);
if(t == null)
{
tvJbAddrs2.setText("");
}
else
{
tvJbAddrs2.setText(t);
}
tvJbPostcode.setText(u);
}
catch (Exception e)
{
Log.e("log_tag", "Error Parsing Data " + e.toString());
}
} //getJobAddress() ends

Geting data from a remote database Android

I'm making an Android app and I'm trying to retrieve data from a remote database.
My question is how can I check if the query result contains data and is not empty?
I'm using JSON but I'm new to it. Here is my code:
public class MainActivity extends Activity {
private TextView txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
txt.setText("Connexion...");
txt.setText(getServerData(strURL));
}
public static final String strURL = "http://.../marecherche/adresse.php";
private String getServerData(String returnString) {
InputStream is = null;
String result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("adresse","adr casa"));
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(strURL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection " + e.toString());
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result " + e.toString());
}
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","raison sociale: "+json_data.getString("raison_social")+
", Adresse: "+json_data.getString("adresse")
);
returnString += "\n\t" + jArray.getJSONObject(i);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data " + e.toString());
}
return returnString;
}
}
and the php file:
<?php
mysql_connect("localhost", "root", "passwd");
mysql_select_db("dbname");
$mots = explode(' ', $_REQUEST['adresse']);
$like = array();
foreach ($mots AS $mot) {
$like[] = ' "%' . mysql_real_escape_string($mot) . '%" ';
}
$condition = implode(' OR adresse LIKE ', $like);
$sql = mysql_query("SELECT * FROM entreprise WHERE adresse like " . $condition);
while ($row = mysql_fetch_assoc($sql))
$output[] = $row;
print(json_encode($output));
mysql_close();
?>
You could just create your own return to check for, something like:
PHP file:
if (is_array($output)) {
print(json_encode($output));
} else
echo "empty";
}
Java:
if (result.equals("empty")) {
return;
}
JSONArray jArray = new JSONArray(result);
// etc
My question is how can I check if the query result contains data and
is not empty?
=> Check result string is null or not before creating JSONArray.

Categories