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.
Related
i want to send all contacts with contact name and number in one row in one array in my android application like
john => "+92312xxxxxxx" ,
Right now i'm using namevaluepairs to post two arrays but it's not working like :
public class ContactList extends Activity {
public TextView outputText;
String phoneNumber = null;
String names = null;
String[] keyValue;
String[] kes;
int Count;
String s = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
outputText = (TextView) findViewById(R.id.textView1);
fetchContacts();
//Http connection
InputStream is=null;
List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>(1);
for (int i = 0; i < Count ; i++)
{
nameValuePairs.add(new BasicNameValuePair("CN[]", keyValue[i]));
nameValuePairs.add(new BasicNameValuePair("names[]",kes[i]));
Log.i("Response", "you sent :" +kes[i]+" :"+ keyValue[i] + "\n ");
}
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.107/older/ContactList.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(ClientProtocolException e)
{
Log.e("ClientProtocol","Log_tag");
e.printStackTrace();
System.out.println("Excep: "+e);
}
catch(IOException e)
{
Log.e("Log_tag","IOException");
e.printStackTrace();
}
String result = "";
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");
}
reader.close();
is.close();
result=sb.toString();
Log.i("Response", "result "+ result);
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
//result = "[{\"0\":\"Muhaimin\",\"1\":\"3\",\"2\":\"o+\"}]";
try
{
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++)
{
s= s +";"+ jArray.getString(i) + "\n";
}
}
catch (Exception e)
{
Log.e("Response", "error fetching indexes" + e);
}
String[] friends= s.split(";");
StringBuffer output = new StringBuffer();
for (int i = 0; i < friends.length; i++)
{
Log.i("List","Your friends namee"+friends[i]);
output.append("\n Your friend's number"+ friends[i]);
}
}
//Fetch Contacts
public void fetchContacts() {
// String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
// Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
//String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
// String DATA = ContactsContract.CommonDataKinds.Email.DATA;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, null);
// Loop for every contact in the phone
Count = cursor.getCount();
if (cursor.getCount() > 0) {
keyValue= new String[Count];
kes= new String[Count];
while (cursor.moveToNext()) {
String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER )));
if (hasPhoneNumber > 0) {
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);
while (phoneCursor.moveToNext())
{
int i=0;
String stu = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
phoneNumber +=":"+ stu;
names +=":" + name;
Log.i("List",stu + name +"\n" );
}
phoneCursor.close();
}
}
}
keyValue = phoneNumber.split(":");
kes = names.split(":");
Log.i("List","24th"+keyValue[23]);
Toast.makeText(getApplicationContext(), "99th "+keyValue[909] ,Toast.LENGTH_LONG).show();
}
PHP after receiving contacts will match them and return only those which have a match with database contacts. And then it returns contacts with names
i'm stuck with sending and receving part
Here is php code
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'verification');
define('DB_USER','root');
define('DB_PASSWORD','');
// 1. Create a database connection
$connection = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD);
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
$PhoneNum= $_POST["CN"];
$i=0;
$j=0;
$friends = array();
$Invite = array();
unset ($PhoneNum[0]);
foreach ($PhoneNum as $i=> $element){
//or do whatever you need to do to that variable
$query="SELECT Number FROM `user` WHERE Number=$element";
$query_exec = mysqli_query($connection ,$query);
if (!$query_exec)
{ echo mysql_error(); }
ELSE {
if(mysqli_num_rows($query_exec)>0)
{
$friends["$j"]= $PhoneNum[$i];
$j++;
}
else
{
;
}}
}
echo (json_encode($friends));
?>
You'll get a URL now that would look like:
www.example.com/yourscript?CN[]=keyValue1&names[]=key1&CN[]=keyValue2&names[]=key2 etc.. going on untill your whole list has looped.
I doubt that is what your PHP script wants to receive, you probably want to send the POST for each time you increment the loop. But thats just conjecture untill you post more information/code.
Instead send a JSON array as the value of the nameValuePair and convert it to a PHP array using json_decode function in the server side.
I have My databases on an xampp server and my activity and php file is given below. The problem in this page is that when I run application it always throws an exception. It always shows my last message that there is "Some problem is there." My submission date is due soon.
This is my Activity file
public class AdminLoginActivity extends Activity {
TextView username, password, message;
Button SignIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_login);
StrictMode.enableDefaults();
username = (TextView) findViewById(R.id.adminusername);
password = (TextView) findViewById(R.id.adminpassword);
message = (TextView) findViewById(R.id.textView5);
SignIn = (Button) findViewById(R.id.adminloginbtn);
SignIn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
checkAdminData();
}
});
}
public void checkAdminData()
{
InputStream isr = null;
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost:1234/adminlogin.php");
try
{
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair> (2);
nameValuePairs.add(new BasicNameValuePair("username", username.getText().toString()));
nameValuePairs.add(new BasicNameValuePair("password", password.getText().toString()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch (ClientProtocolException e)
{
Log.e("log_tag", "Error in Http connection " + e.toString());
message.setText("couldn't connect to database");
}
catch (IOException e)
{
}
String responseText = null;
try
{
String res = isr.toString();
// res = res.replaceAll("\\s+", "");
if (res.equals("1")) {
Intent i = new Intent(this, AdminMainPage.class);
startActivity(i);
}
else{
message.setText("Username or Password incorrect");
}
}
catch (Exception e)
{
Log.e("log_tag", "Sorry!! Incorrect Username or Password " + e.toString());
message.setText("Some problem is there");
}
}
}
PHP file:
<?php
$hostname_localhost ="localhost";
$database_localhost ="sibuilder";
$username_localhost ="root";
$password_localhost ="";
$localhost = mysql_connect($hostname_localhost,$username_localhost,$password_localhost)
or
trigger_error(mysql_error(),E_USER_ERROR);
mysql_select_db($database_localhost, $localhost);
$username = $_POST['username'];
$password = $_POST['password'];
$query_search = "select * from login l, admin a where a.username = '".$username."' AND l.password = '".$password. "'";
$query_exec = mysql_query($query_search) or die(mysql_error());
$rows = mysql_num_rows($query_exec);
//echo $rows;
if($rows == 0) {
echo 0;
}
else {
echo 1;
}
?>
If you want to use your php script instead json format, can refer these questions
Android: AsyncTask to make an HTTP GET Request? Make an HTTP request with android to handle the response. Using AsyncTask is recommended.
my codes is fine, not returning any errors but the values being retrieved are the same as the previous field..for example, if i set table3 to 'HELLO' then table4 is also 'HELLO' which is kinda wrong,i wanted separate values..here is my code...
my SigninActivity:
public class SigninActivity extends AsyncTask<String,Void,String>{
private TextView statusField,roleField, sampleField;
private Context context;
private int byGetOrPost = 0;
//flag 0 means get and 1 means post.(By default it is get.)
public SigninActivity(Context context,TextView statusField,TextView roleField,TextView sampleField,int flag) {
this.context = context;
this.statusField = statusField;
this.roleField = roleField;
this.sampleField = sampleField;
byGetOrPost = flag;
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
if(byGetOrPost == 0){ //means by Get Method
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "http://XXX.XXX.X.X/XXX/ins.php?username="
+username+"&password="+password;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
else{
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link="http://XXX.XXX.X.X/XXX/sel.php";
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter
(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}
#Override
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
this.sampleField.setText(result);
}
}
my select.php file (sel.php):
<?php
$con=mysqli_connect("localhost","root","","db_name");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con,"SELECT role,sample FROM table1 WHERE
username='$username' and password='$password'");
$row = mysqli_fetch_array($result);
$data = $row[0];
if($data){
echo $data;
}
mysqli_close($con);
?>
This is where your problem is:
#Override
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
this.sampleField.setText(result);
}
If you want different values for sampleField and roleField, you should set different values.
Update
I see where your other problem is. In the un-updated PHP source, you are selecting both role and sample from the database table, but you are outputting only role because $data equals $row[0]. If you want sample as well, you would need to retrieve $row[1] as well.
Or you could also use $row["role"] and $row["sample"] to get the values returned from the database table.
<?php
$con=mysqli_connect("localhost","root","","db_name");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con,"SELECT role,sample FROM table1 WHERE
username='$username' and password='$password'");
$row = mysqli_fetch_array($result);
if($row){
// returns a json object in the form
// {"role":"<role-from-database>","sample":"<sample-from-database>"}
$output = array("role" => $row["role"] ,"sample" => $row["sample"]);
echo json_encode($output);
}
mysqli_close($con);
?>
With the updated PHP source, you should process the JSON object in your SigninActivity.
Update 2
#Override
protected void onPostExecute(String result){
String role = "", sample = "";
// read the json object with JsonReader
JsonReader reader = new JsonReader(new StringReader(result));
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (name.equals("role")) {
role = reader.nextString();
} else if (name.equals("sample")) {
sample = reader.nextString();
} else {
reader.skipValue();
}
}
reader.endObject();
// set the text here
}
Let me know if this helps.
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.
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();
?>