简体   繁体   English

使用Android json检查数据库中是否存在数据

[英]check if data exist in database using android json

I'm using Eclipse to develop an app. 我正在使用Eclipse开发应用程序。 I'm trying to check whether the IC exist in database using json. 我正在尝试使用json检查IC是否存在于数据库中。 I do the coding and when I run it i got error. 我进行编码,运行时出现错误。 the db config is correct coz i have tried the config with other file and it working fine. 数据库配置是正确的,因为我尝试了其他文件的配置,并且工作正常。 The plan was: 该计划是:

  1. Input IC in Edit Text : icno_manual 在编辑文本中输入IC:icno_manual
  2. Click button check-in and search for IC in database. 单击按钮签入并在数据库中搜索IC。
  3. If found, return success 如果找到,返回成功
  4. Set the Text View msgResult_manual to "Check-in success" if the TAG_SUCCESS is 1 如果TAG_SUCCESS为1,则将文本视图msgResult_manual设置为“签入成功”

please help me. 请帮我。 here's my xml, java and php.Thanks in advance. 这是我的xml,java和php。 table details: rider [ID(PK)- int, name-varchar, IC(UNIQUE)-varchar] 表详细信息:附加信息[ID(PK)-int,name-varchar,IC(UNIQUE)-varchar]

XML file 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: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="com.example.trialonlistview.MainActivity" >

<TextView
    android:id="@+id/msgResult_manual"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/msgResult_manual"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
    android:id="@+id/icno_manual"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_below="@+id/NRIC_manual"
    android:layout_marginTop="22dp"
    android:ems="10"
    android:inputType="textCapCharacters" >

    <requestFocus />
</EditText>

<Button
    android:id="@+id/btnSearch_manual"
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignRight="@+id/icno_manual"
    android:layout_below="@+id/icno_manual"
    android:layout_marginRight="16dp"
    android:text="@string/btnScan_manual" />

<TextView
    android:id="@+id/NRIC_manual"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="@string/NRIC_manual"
    android:textAppearance="?android:attr/textAppearanceMedium" />

Java edited 1 Java编辑1

package com.example.trialonlistview;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

Button checkIn;
EditText icnotxt;
TextView result;

JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;

private static String icno;

// url to check-in manual
private static String url_manual = "http://192.168.0.25/check/check.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    icnotxt = (EditText)findViewById(R.id.icno_manual);
    checkIn = (Button)findViewById(R.id.btnSearch_manual);
    result = (TextView)findViewById(R.id.msgResult_manual); 

    // check-in button click event
    checkIn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // creating new product in background thread
            new CheckIn().execute();
        }
    });     
}

//manual check-in
//Background Async Task to check-in manually

class CheckIn extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Check-in...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
        //add in
        icno = icnotxt.getText().toString();
    }

    //check-in
    protected String doInBackground(String... args) {

        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("icno", icno));

        JSONObject json = jsonParser.makeHttpRequest(url_manual,
                "POST", params);

        // check log cat from response
        Log.d("Check-in response", json.toString());

        // check for success tag
        int success;
        try {
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                // successfully check-in
                result.setText("Check-in success");
            } else {
                // failed to check-in
                result.setText("Failed");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    protected void onPostExecute(String file_url) {
        // dismiss the dialog once done
        pDialog.dismiss();
    }
}
//manual check-in end

@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;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

PHP 的PHP

<?php
// array for JSON response
$response = array();

// check for required fields
if (isset($_POST['icno'])) {
$icno = $_POST['icno'];

// include db connect class
//require_once __DIR__ . '/db_connect.php'; 
require_once '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

$result = mysql_query("SELECT ID FROM rider WHERE IC = $icno");

// check if found
if (mysql_num_rows($result) > 0) {
    // found
    $response["success"] = 1;
    $response["message"] = "found";

    // echoing JSON response
    echo json_encode($response);
} else {
    // not found
    $response["success"] = 0;
    $response["message"] = "Not found";

    // echoing JSON response
    echo json_encode($response);
}
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";

    // echoing JSON response
    echo json_encode($response);
}
?>

Error edited 1 错误编辑1

11-28 10:55:26.802: E/AndroidRuntime(31123): FATAL EXCEPTION: AsyncTask #1
11-28 10:55:26.802: E/AndroidRuntime(31123): java.lang.RuntimeException: An error occured while executing doInBackground()
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at java.lang.Thread.run(Thread.java:856)
11-28 10:55:26.802: E/AndroidRuntime(31123): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4618)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:839)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.view.View.requestLayout(View.java:15323)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.view.View.requestLayout(View.java:15323)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.view.View.requestLayout(View.java:15323)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.view.View.requestLayout(View.java:15323)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:297)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.view.View.requestLayout(View.java:15323)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.widget.TextView.checkForRelayout(TextView.java:6377)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.widget.TextView.setText(TextView.java:3577)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.widget.TextView.setText(TextView.java:3435)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.widget.TextView.setText(TextView.java:3410)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at com.example.trialonlistview.MainActivity$CheckIn.doInBackground(MainActivity.java:95)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at com.example.trialonlistview.MainActivity$CheckIn.doInBackground(MainActivity.java:1)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-28 10:55:26.802: E/AndroidRuntime(31123):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)

You are accessing UI elements inside doInBackground(). 您正在访问doInBackground()中的UI元素。 you only can use the UI elements on the Main Thread 您只能在主线程上使用UI元素

therefore, make String icno Global within the CheckIn class and then move the following line to onPreExecute() 因此,请在CheckIn类中使String icno Global,然后onPreExecute()移动到onPreExecute()

icno = icnotxt.getText().toString();

EDIT 编辑

return the string to onPostExecute() so the onPostExecute() will handle adding the result text to result textView. 将字符串返回到onPostExecute()以便onPostExecute()将处理将结果文本添加到result textView的过程。 So change the following lines within `doInBackground(): 因此,请在`doInBackground()中更改以下几行:

// check for success tag
    int success;
    try {
        success = json.getInt(TAG_SUCCESS);
        if (success == 1) {
            // successfully check-in
            return "Check-in success";
        } else {
            // failed to check-in
            return "Failed";
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

and change the following in onPostExecute() 并在onPostExecute()更改以下内容

protected void onPostExecute(String file_url) {
    // dismiss the dialog once done
    pDialog.dismiss();
    result.setText(file_url); //file_url will have the following values either Check-in success or failed
}

Give me feedback whether this helped you or not. 给我反馈,这是否对您有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM