Show catched JSON object from PHP in android application - java

I'm going to create a simple register form app that when user insert their username and password, EditText in UI shows the id of their record in database.
My app insert users into database correctly and show JSON output into EditText.
For Example when I insert first user to my database, EditText show this:
{
"id": "1", "0":"1"
}
But, I want show this in EditText:
1 instead of
{
"id" : "1", "0" : "1"
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#00aeef"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="50dp"
android:layout_marginTop="18dp"
android:text="Register Example"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginTop="45dp"
android:text="Username:"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff" />
<EditText
android:id="#+id/edt_username"
android:layout_width="250dp"
android:layout_height="40dp"
android:layout_below="#+id/textView3"
android:layout_centerHorizontal="true"
android:background="#ffffff"
android:ems="10"
android:padding="5dp" >
<requestFocus />
</EditText>
<Button
android:id="#+id/btn_insert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/edt_result"
android:layout_below="#+id/edt_password"
android:layout_marginTop="16dp"
android:background="#ffffff"
android:text="Insert"
android:textColor="#00aeef" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#+id/textView1"
android:layout_below="#+id/edt_username"
android:text="Password:"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff" />
<EditText
android:id="#+id/edt_password"
android:layout_width="250dp"
android:layout_height="40dp"
android:layout_alignLeft="#+id/edt_username"
android:layout_below="#+id/textView2"
android:background="#ffffff"
android:ems="10"
android:padding="5dp" />
<EditText
android:id="#+id/edt_result"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_below="#+id/btn_insert"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:background="#ffffff"
android:ems="10"
android:padding="5dp" />
</RelativeLayout>
InsertClass.java
package com.example.testphp;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
public class InsertClass extends AsyncTask<String, Void, String>{
private Context context;
private ProgressDialog pDialog;
private EditText edt;
private String json = "";
private JSONObject jObj = null;
public InsertClass(Context context, EditText edt)
{
this.context = context;
pDialog = new ProgressDialog(context);
this.edt = edt;
}
#Override
protected void onPreExecute() {
pDialog.setMessage("Loading... Please wait");
pDialog.show();
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
try
{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "http://10.0.2.2:8020/test/test.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;
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
json = sb.toString();
jObj = new JSONObject(json);
return sb.toString();
}
catch(JSONExeption e)
{
return new String("Exeption: " + e.getMessage());
}
catch(Exception e)
{
return new String("Exeption: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
super.onPostExecute(result);
try
{
edt.setText(jObj.getString("id"));
}
catch (JSONExeption e)
{ e.printStackTrace(); }
}
}
MainActivity.java
package com.example.testphp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
String username;
String password;
EditText edtUsername;
EditText edtPassword;
EditText edtResult;
Button btnInsert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnInsert = (Button) findViewById(R.id.btn_insert);
edtPassword = (EditText) findViewById(R.id.edt_password);
edtUsername = (EditText) findViewById(R.id.edt_username);
edtResult = (EditText) findViewById(R.id.edt_result);
btnInsert.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
username = edtUsername.getText().toString();
password = edtPassword.getText().toString();
new InsertClass(MainActivity.this, edtResult).execute(username,password);
}
});
}
#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;
}
}
test.PHP
<?php
$con = mysqli_connect("localhost" , "root" , "","test");
if(mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_errno();
}
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con,"INSERT INTO test (username,pass) VALUES '$username','$password')") or die(mysqli_query($con));
if($result)
{
$id_result = mysqli_query($con,"SELECT id FROM test WHERE username = '$username'") or die(mysqli_query($con));
if($id_result)
{
$id_result = mysqli_fetch_array($id_result);
$response = array("id" => $id_result);
echo json_encode($response);
}
}
mysqli_close($con);
?>
Any suggestion, would be appreciated ...

Your response from PHP for user id=17 is {"id":{"0":"17","id":"17"}}
Try to change in php script
//$response = array("id" => $id_result);
$response["id"] = $id_result["id"];
then your rsponse will be {"id":"17"}

In your class InsertClass and function doInBackground() where you are converting result string to JsonObject like
json = sb.toString();
jObj = new JSONObject(json);
Add code:
String result = jObj.getString ("id");
Return result;

Related

Android Studio - Database fetch to Textview not displaying correctly

I'm trying to display read from table in database, what i have written so far passes the json, however rather than showing in textview - it displays as a short popup, and then disappears.
Activity_tasks.java
package com.example.myapp;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class activity_tasks extends AppCompatActivity {
TextView TextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tasks);
Button button = findViewById(R.id.button1);
button.setOnClickListener(v -> showInfo());
TextView = findViewById(R.id.textView4);
downloadJSON();
}
private void downloadJSON() {
#SuppressLint("StaticFieldLeak")
class DownloadJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
try {
setTextView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL("https://myurl.php");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json).append("\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
DownloadJSON getJSON = new DownloadJSON();
getJSON.execute();
}
private void setTextView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
String[] tasks = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
tasks[i] = obj.getString("Task_title") + " " + obj.getString("task_description");
}
}
private void showInfo() {
AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogStyle);
builder.setIcon(R.drawable.alert);
builder.setTitle(" ");
builder.setMessage("Lockdown sucks, we know.\nThat's why we created W2D.\n\nOver the comings weeks/months, we'll be adding some cool stuff here. So bear with...\n\nStay Home\nProtect the NHS\nSave Lives");
// Create and show the AlertDialog
final AlertDialog alertDialog = builder.create();
alertDialog.show();
}
#Override
public void finish() {
super.finish();
overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right);
}
}
I have a funny feeling this is something about me having a button requesting a pop-up too in the code, perhaps I haven't integrated the 2nd onCreate properly?
The above is linked to a textview on activity_tasks.xml
Example on phone:
activity.xml below:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/black"
android:clickable="true"
tools:context=".MainActivity"
tools:ignore="ExtraText"
android:focusable="true">
>
<ImageView
android:id="#+id/imageView2"
android:layout_width="95dp"
android:layout_height="90dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.946"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.022"
app:srcCompat="#drawable/shortlogo"
tools:ignore="ContentDescription" />
<Button
android:id="#+id/button"
android:layout_width="158dp"
android:layout_height="153dp"
android:background="#drawable/circlebutton"
android:text="#string/hit_me_again"
android:textColor="#000"
android:textSize="8sp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/textView2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.896" />
<Button
android:id="#+id/button1"
android:layout_width="30dp"
android:layout_height="30dp"
android:background="#drawable/alert"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.077"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.06" />
<TextView
android:id="#+id/textView4"
android:layout_width="183dp"
android:layout_height="119dp"
android:textColor="#color/white"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
app:layout_constraintBottom_toTopOf="#+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:paddingBottom="5dp"
android:text="#string/design"
android:textColor="#color/grey"
android:textSize="12sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.092"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="4dp"
android:paddingBottom="5dp"
android:text="#string/version_0_0_1"
android:textColor="#color/grey"
android:textSize="12sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.963"
app:layout_constraintStart_toStartOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
What you are seeing at the bottom is the toast you create in onPostExecute(). You receive the data, but then never update the text of the TextView. In setTextView() you could also do that:
textView.setText(json);
On another note: Don't use AsyncTasks anymore. They are deprecated and way too laborious. Also, to read the Json much more easily, you can use a library like Gson or Moshi.

My application crashes when asynctask process the code in android studio

When i click the login button to process and check my codes it closes the whole app..
logcat error
08-30 00:48:33.876 20672-20672/com.map.laurence.crms2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.map.laurence.crms2, PID: 20672
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at com.map.laurence.crms2.BackgroundWorker.onPostExecute(BackgroundWorker.java:80)
at com.map.laurence.crms2.BackgroundWorker.onPostExecute(BackgroundWorker.java:22)
at android.os.AsyncTask.finish(AsyncTask.java:692)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:709)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:941)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:831)
this class is my problem
BackgroundWorker.java
package com.map.laurence.crms2;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import com.map.laurence.crms2.Menu;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx) {
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://192.168.8.101/AndroidDB/login.php";
if(type.equals("login")) {
try {
String user_name = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
+URLEncoder.encode("user_pass","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result.equals("login success")) {
context.startActivity(new Intent(context, Menu.class));
}else{
alertDialog.setMessage(result);
alertDialog.show();
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
login.java
package com.map.laurence.crms2;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends AppCompatActivity {
public EditText user,pass;
static Login login;
private static final String TAG = "Login";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_login);
login = this;
user = (EditText) findViewById(R.id.etUser);
pass = (EditText) findViewById(R.id.etPass);
}
public static Login getInstance(){
return login;
}
public void onLogin(View v){
String username = user.getText().toString();
String password = pass.getText().toString();
if(username == null || username.equals("") || password == null || password.equals("")) {
Toast.makeText(this,"Empty Fields!",Toast.LENGTH_LONG).show();
}else
{
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, username, password);
}
}
#Override
public void onBackPressed() {
Log.d("back button", "back button pressed");
AlertDialog.Builder ad1=new AlertDialog.Builder(Login.this);
ad1.setMessage("Are you sure you want to Exit? ");
ad1.setCancelable(false);
ad1.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
}
});
ad1.setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
finish();
}
});
AlertDialog alert=ad1.create();
alert.show();
}
}
ive tried clicking the button for toast message and it doesnt crashes.
ive tried replacing this
super.onPostExecute(result);
if(result.equals("login success")) {
context.startActivity(new Intent(context, Menu.class));
}else{
alertDialog.setMessage(result);
alertDialog.show();
}
with this
super.onPostExecute(result);
if(result.equals("login success")) {
alertDialog.setMessage(result);
alertDialog.show();
}else{
alertDialog.setMessage(result);
alertDialog.show();
}
but it gave me the "login Status" from here
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
and no dialog response from the server please help me thanks
here is the login.xml file for those who wanna try it out
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#drawable/backg"
tools:context="com.map.laurence.crms2.Login">
<LinearLayout
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="top|center"
android:layout_alignParentTop="true"
android:layout_marginTop="50dp"
android:layout_centerInParent="true"
android:orientation="vertical">
<ImageView
android:id="#+id/imageView2"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/title"
app:srcCompat="#drawable/logoo"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:gravity="center"
android:text="Apalit Portable" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20dp"
android:gravity="center"
android:text="Census Application" />
</LinearLayout>
<LinearLayout
android:layout_width="292dp"
android:layout_height="265dp"
android:baselineAligned="false"
android:orientation="vertical"
android:layout_marginTop="50dp"
android:layout_below="#+id/title"
android:layout_centerInParent="true"
>
<EditText
android:id="#+id/etUser"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/text_edge"
android:ems="10"
android:hint="#string/username"
android:inputType="textPersonName"
android:textAlignment="viewStart"
android:textSize="25sp" />
<EditText
android:id="#+id/etPass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:background="#drawable/text_edge"
android:ems="10"
android:hint="#string/password"
android:inputType="textPassword"
android:textAlignment="viewStart"
android:textSize="25sp" />
<Button
android:id="#+id/btnLogin"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/login"
android:textColor="#fff"
android:layout_marginTop="50dp"
android:onClick="onLogin"
android:background="#drawable/button_file"
android:textAlignment="center"
/>
</LinearLayout>
</RelativeLayout>
every help will much be appreciated thanks

The output value is returned as NULL instead of values stored in the database table

This is the code to display the carbohydrate content of the meal based on the food and the quantity entered. The PHP code is working fine. When I try to get the output it displays null value.(Carb:null)
GetData.php
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$food = $_GET['food'];
$quantity = $_GET['quantity'];
require_once('dbConnect.php');
$sql = "SELECT * FROM carbcontent WHERE food='$food' & quantity='$quantity'";
$r = mysqli_query($con,$sql);
$res = mysqli_fetch_array($r);
$result = array();
array_push($result,array(
"carb"=>$res['carb']
)
);
echo json_encode(array("result"=>$result));
mysqli_close($con);
}
dbConnect.php
<?php
define('HOST','localhost');
define('USER','root');
define('PASS','');
define('DB','slidingscale');
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
Config.java
public class Config {
public static final String DATA_URL = "http://10.1.56.2 /getData.php?food=&quantity=";
public static final String KEY_CARB ="carb";
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity"
android:weightSum="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="FOOD"
android:id="#+id/textView" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="QUANTITY"
android:id="#+id/textView2" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/editText2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GET"
android:id="#+id/button" />
<TextView
android:id="#+id/textViewResult"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
MainActivity.java
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText editText;
private EditText editText2;
private Button button;
private TextView textViewResult;
private ProgressDialog loading;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
editText2 = (EditText) findViewById(R.id.editText2);
button = (Button) findViewById(R.id.button);
textViewResult = (TextView) findViewById(R.id.textViewResult);
button.setOnClickListener(this);
}
private void getData() {
String food = editText.getText().toString().trim();
if (food.equals("")) {
Toast.makeText(this, "Please enter an food", Toast.LENGTH_LONG).show();
return;
}
String quantity = editText2.getText().toString().trim();
if (quantity.equals("")) {
Toast.makeText(this, "Please enter quantity", Toast.LENGTH_LONG).show();
return;
}
loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);
String url = Config.DATA_URL+editText.getText().toString().trim()+editText2.getText().toString().trim();
StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
loading.dismiss();
showJSON(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void showJSON(String response){
String carb="";
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
JSONObject collegeData = result.getJSONObject(0);
carb = collegeData.getString(Config.KEY_CARB);
} catch (JSONException e) {
e.printStackTrace();
}
textViewResult.setText("\nCarb:\t" +carb);
}
#Override
public void onClick(View v) {
getData();
}
}
The immediate cause of your problem most likely is that you are wrapping the quantity as a string, in single quotes, rather than treating it as a number. If so, then the following should work:
$sql = "SELECT * FROM carbcontent WHERE food='$food' & quantity=$quantity";
But you should seriously consider using prepared statements, which will free you from worrying over the type of data to be included in your query.
Did you possibly forget to select a database?
$db = mysql_select_db('your_db');
Put this before making the query in your PHP code.

Send and receive json obj in Android

I am currently working with an app that can access an online game to acquire information of my account. I need to use JSON to communicate with the server. I used the following code to try to communicate with the server, but there are no responds from the server. I also noticed that the httpclient and some other popular class were deprecated and I can't find some proper tutorial to teach me on this topic. Any help is appreciated.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="deardanielxd.travain2.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Username : "
android:id="#+id/Username_Lbl"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:editable="true"
android:minHeight="20dp"
android:layout_alignBottom="#+id/Username_Field"
android:layout_toStartOf="#+id/Username_Field"
android:layout_alignEnd="#+id/Password_Lbl" />
<EditText
android:layout_width="wrap_content"
android:layout_height = "40dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/Username_Field"
android:editable="true"
android:contextClickable="true"
android:textIsSelectable="true"
android:enabled="true"
android:focusable="true"
android:clickable="true"
android:inputType="text"
android:minHeight="40dp"
android:layout_alignParentTop="true"
android:layout_alignEnd="#+id/Load_Btn"
android:layout_toEndOf="#+id/Password_Lbl" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Password : "
android:id="#+id/Password_Lbl"
android:layout_below="#+id/Username_Lbl"
android:layout_alignParentStart="true"
android:minHeight="20dp"
android:layout_alignBottom="#+id/Password_Field" />
<EditText
android:layout_width="wrap_content"
android:layout_height="40dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:id="#+id/Password_Field"
android:password="true"
android:editable="true"
android:textIsSelectable="true"
android:enabled="true"
android:focusable="true"
android:contextClickable="true"
android:clickable="true"
android:inputType="text"
android:minHeight="40dp"
android:layout_below="#+id/Username_Field"
android:layout_alignParentEnd="true"
android:layout_alignStart="#+id/Username_Field" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Load"
android:id="#+id/Load_Btn"
android:layout_alignParentEnd="true"
android:layout_alignBottom="#+id/spinner"
android:layout_below="#+id/Password_Field" />
<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:spinnerMode="dropdown"
android:layout_alignParentStart="true"
android:layout_toStartOf="#+id/Load_Btn"
android:layout_below="#+id/Password_Lbl" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/SysMsg"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:text="System : "
android:textColor="#FF0000" />
<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/scrollView"
android:layout_below="#+id/spinner"
android:layout_alignParentStart="true"
android:layout_above="#+id/SysMsg"
android:layout_alignParentEnd="true" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/OutPut"
android:enabled="true" />
</ScrollView>
MainActivity.java
package deardanielxd.travain2;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
public class MainActivity extends AppCompatActivity {
Spinner spinner;
EditText Username, Password;
Button Load_Btn;
TextView Main_Output;
TextView Sys_Output;
String server = "";
boolean debug = true;
PlayerInfo curr = new PlayerInfo();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SetupGadget();
attachListener();
}
private void SetupGadget() {
spinner = (Spinner) findViewById(R.id.spinner);
Username = (EditText) findViewById(R.id.Username_Field);
Password = (EditText) findViewById(R.id.Password_Field);
Load_Btn = (Button) findViewById(R.id.Load_Btn);
Main_Output = (TextView) findViewById(R.id.OutPut);
Sys_Output = (TextView) findViewById(R.id.SysMsg);
ArrayAdapter adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,Constants.Servers);
spinner.setAdapter(adapter);
}
private void attachListener() {
Load_Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (debug) {
MainOutput( "Username : " + Username.getText());
MainOutput( "Password : " + Password.getText());
MainOutput( "Server : " + server);
MainOutput( "Internet Connection : " + (InternetAccess()?"Yes":"No"));
MainOutput( "" );
}
new test(MainActivity.this).execute();
}
});
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
server = parent.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void SystemOutput(String output) {
Sys_Output.setText("System : " + output);
}
public void MainOutput(String output) {
Main_Output.append("\n" + output);
}
private boolean InternetAccess() {
ConnectivityManager cm =
(ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting();
}
public class test extends AsyncTask<Void, Void, Void>
{
private MainActivity MA;
test(MainActivity ma) {
MA = ma;
}
#Override
protected Void doInBackground(Void... n) {
try {
URL url = new URL("http://"+MA.server+"/api/external.php");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type","application/json");
urlConnection.setRequestProperty("Host", "android.schoolportal.gr");
urlConnection.setRequestMethod("POST");
urlConnection.setUseCaches(false);
urlConnection.connect();
OutputStream printout = new DataOutputStream(urlConnection.getOutputStream ());
printout.write(URLEncoder.encode(this.getObj().toString(),"UTF-8").getBytes());
printout.flush ();
printout.close ();
try {
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader r = new BufferedReader(new InputStreamReader(in));
StringBuilder total = new StringBuilder(in.available());
String line;
while ((line = r.readLine()) != null) {
total.append(line).append('\n');
}
MA.MainOutput(total.toString());
MA.MainOutput("End of Doc");
} finally {
urlConnection.disconnect();
return null;
}
} catch (java.net.MalformedURLException e) {
} catch (java.io.IOException e) {
};
return null;
}
private JSONObject getObj() {
JSONObject jobj = new JSONObject();
try {
jobj.put("email","funckybuggy#gmail.com");
jobj.put("siteName","EasyTravian");
jobj.put("sitUrl","testing.com");
jobj.put("public",false);
} catch (org.json.JSONException e) {
}
return jobj;
}
}
public PlayerInfo getCurrentPlayerInfo() {
return this.curr;
}
public void UpdateCurr() {
this.curr.Username = this.Username.getText().toString();
this.curr.Password = this.Password.getText().toString();
this.curr.Server = this.server;
}
}
Constants.java
public class Constants {
public static final String[] Servers = {
"ts1.travian.hk",
"ts2.travian.hk",
"ts20.travian.hk",
"tx3.travian.hk",
"ts4.travian.hk",
"ts19.travian.hk",
"ts3.travian.hk",
"ts6.travian.hk",
"ts5.travian.hk"
};
}
I don't think you should encode the body of the message.
The reason it is called "URLEncoder" is because it is used to encode a URL but this is the body of your message.
Also, the internal try block you have is redundant and also you should change the request method to GET in the middle of the request.
There's no need to flush the bytes.
Remember that with a POST request, nothing is sent until you read the response using your InputStream.
You should use Volley Library for it.
It's very good for the Rest API's.
And managing server calls is simple with it.
Add the library by compiling
compile 'com.android.volley:volley:1.0.0'
then make a Singleton class to handle all the volley requests.
Volley provides JsonArrayRequest and JsonObjectRequest which are very helpful during network calls.
Here is volley singleton class
public class MyApplication extends Application
{
private RequestQueue mRequestQueue;
private static MyApplication mInstance;
#Override
public void onCreate()
{
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance()
{
return mInstance;
}
public RequestQueue getReqQueue()
{
if (mRequestQueue == null)
{
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToReqQueue(Request<T> req, String tag)
{
getReqQueue().add(req);
}
public <T> void addToReqQueue(Request<T> req)
{
getReqQueue().add(req);
}
public void cancelPendingReq(Object tag)
{
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
Add this to your application tag in manifest
<application
android:name="MyApplication">
This is a sample JsonObjectRequest
JsonObjectRequest request = new JsonObjectRequest("requestMethod","url","input_data",
new Response.Listener<JSONObject>()
{
#Override
public void onResponse(JSONObject response)
{
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
}
});
MyApplication.getInstance().addToReqQueue(request);

Did not Pop appears in AutoCompleteTextView

Hereby i have design this activity, My data from webservice is properly working, but i can't get the dropdownlist. here i convert the arraylist into String array for show the result in autocomplete.Kindly help me. Thanks in Advance.
File:proprety.xml
<?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:background="#drawable/bg"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/menubar12"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:background="#drawable/property_header"
android:gravity="left|center"
android:orientation="horizontal" >
<Button
android:id="#+id/btn_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:background="#drawable/home"
android:onClick="myclick_home" />
<LinearLayout
android:id="#+id/menubar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right|center"
android:orientation="horizontal" >
<Button
android:id="#+id/btn_logout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:background="#drawable/logout"
android:onClick="myclick_logout" />
</LinearLayout>
</LinearLayout>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="#+id/bg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginTop="5dp"
android:orientation="vertical" >
<AutoCompleteTextView
android:id="#+id/et_propertyact_propertyname"
android:layout_width="match_parent"
android:layout_height="28dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="10dp"
android:background="#drawable/property_text"
android:cursorVisible="true"
android:ems="10"
android:hint="Property Name"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:singleLine="true"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:textSize="14sp"
android:textStyle="bold" >
<requestFocus />
</AutoCompleteTextView>
<AutoCompleteTextView
android:id="#+id/et_propertyact_blockname"
android:layout_width="match_parent"
android:layout_height="28dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="10dp"
android:background="#drawable/block_text"
android:cursorVisible="true"
android:ems="10"
android:hint="Block Name"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:singleLine="true"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:textSize="14sp"
android:textStyle="bold" >
</AutoCompleteTextView>
<AutoCompleteTextView
android:id="#+id/et_propertyact_appartmentname"
android:layout_width="match_parent"
android:layout_height="28dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:layout_marginTop="10dp"
android:background="#drawable/apartment"
android:cursorVisible="true"
android:ems="10"
android:hint="Apartment Name"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:singleLine="true"
android:textColor="#ffffff"
android:textColorHint="#ffffff"
android:textSize="14sp"
android:textStyle="bold" >
</AutoCompleteTextView>
<LinearLayout
android:id="#+id/bg_buttons"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center"
android:orientation="vertical"
android:padding="5dp" >
<Button
android:id="#+id/btn_propertyact_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/view_button" />
</LinearLayout>
</LinearLayout>
</ScrollView>
<ListView
android:id="#+id/property_listView"
android:layout_width="wrap_content"
android:layout_height="0dip"
android:layout_marginLeft="6dp"
android:layout_marginRight="6dp"
android:layout_marginTop="6dp"
android:layout_weight="1"
android:cacheColorHint="#00000000"
android:clickable="true"
android:divider="#drawable/cellborder" android:dividerHeight="1dp" android:focusable="true" >
</ListView>
</LinearLayout>
File:PropertyActivity.Java
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONObject;
import com.example.webservice.JSONfunction_JSONArray;
import com.example.webservice.JSONfunction_JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.MultiAutoCompleteTextView;
import android.widget.SimpleAdapter;
public class PropertyActivity extends Activity {
/* ====Components Declaration Part Begins here======= */
private ListView property_listView;
private ListView list_property;
private Button btn_view;
private AutoCompleteTextView propertyname, blockname, apartmentname;
private static final String TAG = "AppSquare";
/* ====ServiceVariables Declarations Part ======= */
JSONArray j_array,j_array1;
JSONObject j_obj,j_obj1;
ArrayList<HashMap<String, String>> arrList_proprty_list = new ArrayList<HashMap<String, String>>();
public static ArrayList<String> arrList_property_names = new ArrayList<String>();
public static ArrayList<String> arrList_block_names = new ArrayList<String>();
public static ArrayList<String> arrList_apartment_names = new ArrayList<String>();
public static ArrayList<String> arrList_property_names_id= new ArrayList<String>();
public static ArrayList<String> arrList_block_names_id= new ArrayList<String>();
public static ArrayList<String> arrList_apartment_names_id= new ArrayList<String>();
private ArrayAdapter<String> PropAdapter;
private ArrayAdapter<String> BlockAdapter;
private ArrayAdapter<String> ApartmentAdapter;
public static String[] arr_Prop_name;
public static String[] arr_block_name;
public static String[] arr_apartment_name;
/* ====API Declarations Part ======= */
public static final String ip = "192.168.0.6";
String API_propSelect = "http://" + ip + "/APP2/propertySelect.php";
String API_blockSelect = "http://" + ip + "/APP2/blockSelect.php";
String API_apartmentSelect = "http://" + ip + "/APP2/apartmentSelect.php";
String API_propDetails = "http://" + ip + "/App2/propertyDetails.php";
/* ====OnClick Declarations Part ======= */
/* ====OnClick Definition Part Begins here======= */
public void myclick_logout(View v) {
AlertDialog.Builder builder2 = new AlertDialog.Builder(
PropertyActivity.this);
builder2.setTitle("Warning");
builder2.setMessage("Closing Application..");
builder2.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// finish();
// System.exit(0);
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
finish();
}
});
builder2.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder2.show();
}
public void myclick_home(View v) {
startActivity(new Intent(PropertyActivity.this, DashBoardActivity.class));
}
/* ====OnCreate Definition Part Begins here======= */
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.property_activity);
getPrefernces();
new PropName().execute();
new BlockName().execute();
new ApartmentName().execute();
setValue_AutoComplete();
Viewbtn_action();
}
public void getPrefernces()
{
property_listView = (ListView) findViewById(R.id.property_listView);
propertyname = (AutoCompleteTextView) findViewById(R.id.et_propertyact_propertyname);
blockname = (AutoCompleteTextView) findViewById(R.id.et_propertyact_blockname);
apartmentname = (AutoCompleteTextView) findViewById(R.id.et_propertyact_appartmentname);
btn_view = (Button) findViewById(R.id.btn_propertyact_view);
}
public void setValue_AutoComplete()
{
/*-------Load Data into PropertList-----*/
arr_Prop_name = arrList_property_names.toArray(new String[arrList_property_names.size()]);
PropAdapter = new ArrayAdapter<String>(PropertyActivity.this,android.R.layout.simple_dropdown_item_1line,arr_Prop_name);
propertyname.setAdapter(PropAdapter);
propertyname.getDropDownBackground().setAlpha(255);
propertyname.setThreshold(1);
/*------Load Data into Block List------*/
arr_block_name = arrList_block_names.toArray(new String[arrList_block_names.size()]);
BlockAdapter = new ArrayAdapter<String>(PropertyActivity.this,android.R.layout.simple_dropdown_item_1line,arr_block_name);
blockname.setAdapter(BlockAdapter);
blockname.getDropDownBackground().setAlpha(255);
blockname.setThreshold(1);
/*------Load Data into apartment List------*/
arr_apartment_name = arrList_apartment_names.toArray(new String[arrList_apartment_names.size()]);
ApartmentAdapter = new ArrayAdapter<String>(PropertyActivity.this,android.R.layout.simple_dropdown_item_1line,arr_apartment_name);
apartmentname.setAdapter(ApartmentAdapter);
apartmentname.getDropDownBackground().setAlpha(255);
apartmentname.setThreshold(1);
}
private void Viewbtn_action() {
btn_view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
class PropName extends AsyncTask<Void, Void, String>
{
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
try{
System.out.println("In Background...PropName");
System.out.println(API_propSelect);
j_obj=JSONfunction_JSONObject.getJSONfromURL(API_propSelect);
Log.d(TAG, "JSON_RES" + j_obj);
j_array = j_obj.getJSONArray("property");
for (int i = 0; i < j_array.length(); i++)
{
j_obj1 = j_array.getJSONObject(i);
String id= j_obj1.getString("Id");
String value=j_obj1.getString("Value");
System.out.println("Id------>"+id);
System.out.println("Value------>"+value);
//arrList_property_names_id.add(id);
arrList_property_names.add(value);
//System.out.println("Value in array list------>"+arrList_property_names_id);
System.out.println("Value in array list------>"+arrList_property_names);
}
} catch (Exception e) {
Log.d("Error", "Error in API" + e.getStackTrace().toString());
}
return "";
}
}
class BlockName extends AsyncTask<Void, Void, String>
{
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
try{
System.out.println("In Background...BlockName");
System.out.println(API_blockSelect);
j_obj=JSONfunction_JSONObject.getJSONfromURL(API_blockSelect);
Log.d(TAG, "JSON_RES" + j_obj);
j_array = j_obj.getJSONArray("apartment");
for (int i = 0; i < j_array.length(); i++)
{
j_obj1 = j_array.getJSONObject(i);
String id= j_obj1.getString("Id");
String value=j_obj1.getString("Value");
System.out.println("Id------>"+id);
System.out.println("Value------>"+value);
//arrList_block_names_id.add(id);
arrList_block_names.add(value);
//System.out.println("Value in array list------>"+arrList_block_names_id);
System.out.println("Value in array list------>"+arrList_block_names);
}
} catch (Exception e) {
Log.d("Error", "Error in API" + e.getStackTrace().toString());
}
return "";
}
}
class ApartmentName extends AsyncTask<Void, Void, String>
{
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
try{
System.out.println("In Background...ApartmentName");
System.out.println(API_apartmentSelect);
j_obj=JSONfunction_JSONObject.getJSONfromURL(API_apartmentSelect);
Log.d(TAG, "JSON_RES" + j_obj);
j_array = j_obj.getJSONArray("block");
for (int i = 0; i < j_array.length(); i++)
{
j_obj1 = j_array.getJSONObject(i);
String id= j_obj1.getString("Id");
String value=j_obj1.getString("Value");
System.out.println("Id------>"+id);
System.out.println("Value------>"+value);
//arrList_apartment_names_id.add(id);
arrList_apartment_names.add(value);
//System.out.println("Value in array list------>"+arrList_apartment_names_id);
System.out.println("Value in array list------>"+arrList_apartment_names);
}
} catch (Exception e) {
Log.d("Error", "Error in API" + e.getStackTrace().toString());
}
return "";
}
}
}
Finally got answer
1.Implements Texwatcher
2.override the OnTextChanged();
Thats it...
public class PropertyActivity extends Activity implements TextWatcher{
#Override
protected void onCreate(Bundle savedInstanceState) {
propertyname = (AutoCompleteTextView) findViewById(R.id.et_propertyact_propertyname);
propertyname.addTextChangedListener(this);
blockname = (AutoCompleteTextView) findViewById(R.id.et_propertyact_blockname);
blockname.addTextChangedListener(this);
apartmentname = (AutoCompleteTextView) findViewById(R.id.et_propertyact_appartmentname);
apartmentname.addTextChangedListener(this);
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
PropAdapter = new ArrayAdapter<String>(PropertyActivity.this,R.layout.my_autolist_item,arr_Prop_name);
// propertyname.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
propertyname.getDropDownBackground().setAlpha(255);
propertyname.setThreshold(1);
propertyname.setAdapter(PropAdapter);
BlockAdapter = new ArrayAdapter<String>(PropertyActivity.this,R.layout.my_autolist_item,arr_block_name);
// blockname.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
blockname.getDropDownBackground().setAlpha(255);
blockname.setThreshold(1);
blockname.setAdapter(BlockAdapter);
ApartmentAdapter = new ArrayAdapter<String>(PropertyActivity.this,R.layout.my_autolist_item,arr_apartment_name);
// apartmentname.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
apartmentname.getDropDownBackground().setAlpha(255);
apartmentname.setThreshold(1);
apartmentname.setAdapter(ApartmentAdapter);
}
}

Categories