I amm new in android. I want to get value of my id using json to my php server
so I can get all data i want from my database.
This is query I want to do
$query1=mysqli_query($con,"SELECT * FROM jadwal_matakuliah WHERE nim_mhs ='$id'");
my php code
<?php
include "koneksi.php";
$username = $_POST["id"];
$query1=mysqli_query($con,"SELECT * FROM jadwal_matakuliah WHERE nim_mhs ='$id'");
if($query)
{
while($row=mysqli_fetch_array($query))
{
$flag[]=$row;
}
print(json_encode($flag));
}
mysqli_close($con);
?>
my android code
String id, username;
SharedPreferences sharedpreferences;
public static final String TAG_ID = "id";
public static final String TAG_USERNAME = "username";
String urladdress="http://10.0.2.2/multi/menu_mhs.php";
String[] name;
String[] jam;
String[] email;
String[] imagepath;
ListView listView;
BufferedInputStream is;
String line=null;
String result=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
listView=(ListView)findViewById(R.id.lview);
StrictMode.setThreadPolicy((new StrictMode.ThreadPolicy.Builder().permitNetwork().build()));
collectData();
CustomListView customListView=new CustomListView(this,name,email,imagepath,jam);
listView.setAdapter(customListView);
// getSupportActionBar().setTitle("MHS");
txt_id = (TextView) findViewById(R.id.txt_id);
txt_username = (TextView) findViewById(R.id.txt_username);
btn_logout = (Button) findViewById(R.id.btn_logout);
sharedpreferences = getSharedPreferences(Login.my_shared_preferences, Context.MODE_PRIVATE);
id = getIntent().getStringExtra(TAG_ID);
username = getIntent().getStringExtra(TAG_USERNAME);
txt_id.setText("" + id);
txt_username.setText("( " + username +" )");
}
private void collectData() {
//Connection
try {
URL url = new URL(urladdress);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
is = new BufferedInputStream(con.getInputStream());
} catch (Exception ex) {
ex.printStackTrace();
}
//content
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception ex) {
ex.printStackTrace();
}
//JSON
try {
JSONArray ja = new JSONArray(result);
JSONObject jo = null;
name = new String[ja.length()];
jam = new String[ja.length()];
email = new String[ja.length()];
imagepath = new String[ja.length()];
for (int i = 0; i <= ja.length(); i++) {
jo = ja.getJSONObject(i);
name[i] = jo.getString("nama_matakuliah");
email[i] = jo.getString("dosen");
imagepath[i] = jo.getString("photo");
jam[i] = jo.getString("jadwal");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
You can send the id as a query parameter with your URL,
ie if your URL is example.com/hello then
you can call it as example.com/hello?id=your_id
Related
I'm trying to connect an app withe login and register through the use of php this is the code of the android connection part ,the url used ftp to connect the mysql database:
public class BackgroundTask extends AsyncTask<String,Void,String> {
SharedPreferences preferences;
SharedPreferences.Editor editor;
Context context;
BackgroundTask(Context ctx){
this.context = ctx;
}
#Override
protected String doInBackground(String... params) {
preferences = context.getSharedPreferences("MYPREFS", Context.MODE_PRIVATE);
editor = preferences.edit();
editor.putString("flag","0");
editor.commit();
String urlRegistration = "ftp://remoteaddress/site/wwwroot/classes/LoginAndRegister-register.php";
String urlLogin = "ftp://remoteaddress/site/wwwroot/classes/LoginAndRegister-login.php";
String task = params[0];
if(task.equals("register")){
String regName = params[1];
String regEmail = params[2];
String regPassword = params[3];
try {
URL url = new URL(urlRegistration);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
String myData = URLEncoder.encode("identifier_name","UTF-8")+"="+URLEncoder.encode(regName,"UTF-8")+"&"
+URLEncoder.encode("identifier_email","UTF-8")+"="+URLEncoder.encode(regEmail,"UTF-8")+"&"
+URLEncoder.encode("identifier_password","UTF-8")+"="+URLEncoder.encode(regPassword,"UTF-8");
bufferedWriter.write(myData);
bufferedWriter.flush();
bufferedWriter.close();
InputStream inputStream = httpURLConnection.getInputStream();
inputStream.close();
editor.putString("flag","register");
editor.commit();
return "Successfully Registered " + regName;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
if(task.equals("login")){
String loginEmail = params[1];
String loginPassword = params[2];
try {
URL url = new URL(urlLogin);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
//send the email and password to the database
OutputStream outputStream = httpURLConnection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
String myData = URLEncoder.encode("identifier_loginEmail","UTF-8")+"="+URLEncoder.encode(loginEmail,"UTF-8")+"&"
+URLEncoder.encode("identifier_loginPassword","UTF-8")+"="+URLEncoder.encode(loginPassword,"UTF-8");
bufferedWriter.write(myData);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//get response from the database
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String dataResponse = "";
String inputLine = "";
while((inputLine = bufferedReader.readLine()) != null){
dataResponse += inputLine;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
System.out.println("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
System.out.println(dataResponse);
editor.putString("flag","login");
editor.commit();
return dataResponse;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
//This method willbe called when doInBackground completes... and it will return the completion string which
//will display this toast.
#Override
protected void onPostExecute(String s) {
String flag = preferences.getString("flag","0");
if(flag.equals("register")) {
Toast.makeText(context,s,Toast.LENGTH_LONG).show();
}
if(flag.equals("login")){
String test = "false";
String name = "";
String email = "";
String[] serverResponse = s.split("[,]");
test = serverResponse[0];
name = serverResponse[1];
email = serverResponse[2];
if(test.equals("true")){
editor.putString("name",name);
editor.commit();
editor.putString("email",email);
editor.commit();
Intent intent = new Intent(context,LogginIn.class);
context.startActivity(intent);
}else{
display("Login Failed...", "That email and password do not match our records :(.");
}
}else{
display("Login Failed...","Something weird happened :(.");
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
public void display(String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
}
here is the php connection:
<?
$hostname = "us-cdbr-azure-southcentral-f.cloudapp.net";
$username = "XXXXX";
$dbname = "db";
$password = "word";
//Create connection
$conn = mysql_connect($hostname, $username, $password);
$selectdb=mysql_select_db($dbname);
//Check connection
if(!$conn){
//die("Connectioned failed!" . mysql_connect_error());
}
else{
//echo "Connect success!";
}
?>
and the login.php the password is encrypted so i used sha1()."XXXX" to try to get the password:
<?php
require "LoginAndRegister-connection.php";
$user_email = $_POST["identifier_loginEmail"];
$user_pass = $_POST["identifier_loginPassword"];
$mysql_query = "SELECT * FROM usuarios WHERE email = '$user_email'
AND senha = '$user_pass'";
$result = mysql_query($conn,$mysql_query);
//check the result
if(mysql_num_rows($result)>0){
$row = mysql_fetch_assoc($result);
$name = $row["name"];
$email = $row["email"];
//Here is the specially formatted string response.. ie: "ServerResponse".
//It is of the form: "boolean,email,name"
echo "true,".$email.",".$name;
}
else{
echo "Login was not successful... :(";
}
?>
when i run the code this error appears when i try to login in the app :java.lang.ClassCastException: sun.net.www.protocol.ftp.FtpURLConnection cannot be cast to java.net.HttpURLConnection
could someone show where i made the mistakes?
I build an android application using "Android Studio" that upload images after compress and encode it using base64 and save it at server in string format, then download it (PHP send images strings using JSON). after decoding the image some image is showing normally but other not (the most images doesn't appear).
I search and try many posted solution, but nothing worked properly, please any help.
this is my android java code:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final int RESULT_LOAD_IMAGE = 1;
ImageView imagetoupload, imagetodownload;
Button up_bt, dw_bt;
EditText etuploadname, etdownname;
String get_etdownname, down_user_pic, encodedImage;
Bitmap decodedByte;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imagetoupload = (ImageView) findViewById(R.id.imagetoupload);
imagetodownload = (ImageView) findViewById(R.id.imagetodownload);
up_bt = (Button) findViewById(R.id.up_bt);
dw_bt = (Button) findViewById(R.id.dw_bt);
etuploadname = (EditText) findViewById(R.id.etuploadname);
etdownname = (EditText) findViewById(R.id.etdownname);
up_bt.setOnClickListener(this);
dw_bt.setOnClickListener(this);
imagetoupload.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.imagetoupload:
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
break;
case R.id.up_bt:
Bitmap image = ((BitmapDrawable) imagetoupload.getDrawable()).getBitmap();
new UploadImage(image, etuploadname.getText().toString()).execute();
break;
case R.id.dw_bt:
get_etdownname = etdownname.getText().toString();
DownloadBackGround b = new DownloadBackGround();
b.execute(get_etdownname);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
Uri selectedimage = data.getData();
imagetoupload.setImageURI(selectedimage);
}
}
private class UploadImage extends AsyncTask<Void, Void, Void> {
Bitmap image;
String name;
public UploadImage(Bitmap image, String name) {
this.image = image;
this.name = name;
}
#SuppressWarnings("ResourceType")
#Override
protected Void doInBackground(Void... params) {
String data = "";
int tmp;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);
Log.d("Me", encodedImage);
try {
URL url = new URL("------ my url -------");
String urlParams = "image=" + encodedImage + "&name=" + name;
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(urlParams.getBytes());
os.flush();
os.close();
InputStream is = httpURLConnection.getInputStream();
while ((tmp = is.read()) != -1) {
data += (char) tmp;
}
is.close();
httpURLConnection.disconnect();
Log.e("Me", data + "");
// return data;
} catch (IOException e) {
e.printStackTrace();
// return "Exception: " + e.getMessage();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Toast.makeText(getApplicationContext(), "image uploaded", Toast.LENGTH_LONG).show();
byte[] decodedString = Base64.decode(encodedImage.getBytes(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
imagetodownload.setImageBitmap(decodedByte);
imagetodownload.setImageBitmap(decodedByte);
}
}
////////////////////////////download /////////////////////////////
class DownloadBackGround extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String name_pic = params[0];
try {
URL url = new URL("------ my url ------");
String urlParams = "name=" + name_pic;
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(urlParams.getBytes());
os.flush();
os.close();
InputStream is = httpURLConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder buffer = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
is.close();
httpURLConnection.disconnect();
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "Exception: " + e.getMessage();
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result.equals("2")) {
Log.e("Me", "No picture in this name");
} else {
Log.e("Me", result);
try {
JSONObject parentObject = new JSONObject(result);
JSONArray parentArray = parentObject.getJSONArray("result");
JSONObject finalObject = parentArray.getJSONObject(0);
down_user_pic = finalObject.getString("pic_byte");
} catch (JSONException e) {
e.printStackTrace();
}
//// decode picture and set here
Log.d("Me", down_user_pic);
byte[] decodedString = Base64.decode(down_user_pic.getBytes(), Base64.DEFAULT);
decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
imagetodownload.setImageBitmap(decodedByte);
}
}
}
///////////////////////////////Download //////////////////////////
and this is my uploading php code:
<?php require "init.php";
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$image = $_REQUEST["image"];
$name = $_POST["name"];
$image = str_replace(" ", "+", $image);
$id= uniqid();
//$decodedImage = base64_decode("$image");
$sql = "INSERT INTO `pictures` (`id`, `pic_id`, `pic_byte`) VALUES ('".$id."', '".$name."', '".$image."');";
if(!mysqli_query($con, $sql)){
}
?>
and this is my downloading php code:
<?php
require "init.php";
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$name = $_POST["name"];
$id= uniqid();
$sql = "SELECT * FROM pictures WHERE `pic_id`='".$name."'";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('pic_byte'=>$row[2]));
}
$string1 = '{"result":[]}';
$string2 = json_encode(array("result"=>$result));
$pos = strspn($string1 ^ $string2, "\0");
if($string1[$pos]=="" && $string2[$pos] == ""){
echo "2";
}else {
echo $string2;
}
?>
this logcat was show:
04-20 11:39:31.184 18472-18472/com.example.aly.updownpic D/dalvikvm: GC_FOR_ALLOC freed 1765K, 44% free 7473K/13340K, paused 17ms, total 21ms
04-20 11:39:31.184 18472-18472/com.example.aly.updownpic I/dalvikvm-heap: Grow heap (frag case) to 13.192MB for 4080016-byte allocation
04-20 11:39:31.234 18472-18472/com.example.aly.updownpic D/skia: --- decoder->decode returned false
UPDATE
I used JPEG but less than half of the picture is show
this is the screenshot of the picture
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.
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.