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

I'm using Eclipse to develop an app. I'm trying to check whether the IC exist in database using json. 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
  2. Click button check-in and search for IC in database.
  3. If found, return success
  4. Set the Text View msgResult_manual to "Check-in success" if the TAG_SUCCESS is 1

please help me. here's my xml, java and php.Thanks in advance. table details: rider [ID(PK)- int, name-varchar, IC(UNIQUE)-varchar]

XML file

<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

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
// 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

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)
dongsunny1113
dongsunny1113 'Stringicno=icnotxt.getText()。toString();'
接近 6 年之前 回复
douju1280
douju1280 主要活动中哪条线是74?
接近 6 年之前 回复

1个回答



您正在访问doInBackground()中的UI元素。 你只能使用主线程上的UI元素</ p>

因此,在 CheckIn </ code>类中make String icno </ code> Global,然后移动 下一行到 onPreExecute()</ code> </ p>

  icno = icnotxt.getText()。toString(); 
</ code> </ pre> \ n

编辑</ strong> </ p>

将字符串返回 onPostExecute()</ code>,以便 onPostExecute()</ code >将处理将结果文本添加到 result </ code> textView。 因此,在`doInBackground()中更改以下行:</ p>

  //检查成功标记
int成功;
尝试{
success = json.getInt(TAG_SUCCESS) ;
if(success == 1){
//成功签到
返回“签入成功”;
}其他{
//无法签入
返回“失败”;

}
} catch(JSONException e){
e.printStackTrace();
}
</ code> </ pre>

并在 onPostExecute中更改以下内容( )</ code> </ p>

  protected void onPostExecute(String file_url){
//一旦完成就关闭对话框
pDialog.dismiss();
result.setText( FILE_URL); // file_url将具有以下值:签入成功或失败
}
</ code> </ pre>

向我提供反馈是否对您有所帮助。</ p> \ n </ div>

展开原文

原文

You are accessing UI elements inside doInBackground(). you only can use the UI elements on the Main Thread

therefore, make String icno Global within the CheckIn class and then move the following line to onPreExecute()

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

EDIT

return the string to onPostExecute() so the onPostExecute() will handle adding the result text to result textView. So change the following lines within `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()

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.

duanshan3331
duanshan3331 很高兴它与你合作..
接近 6 年之前 回复
drvxclagw656708070
drvxclagw656708070 是! 有用! 非常感谢..但是result.setText(“file_url”)应该是file_url,没有双引号
接近 6 年之前 回复
dougongyou7364
dougongyou7364 好。 我会尝试编辑过的
接近 6 年之前 回复
duanlong4890
duanlong4890 在doInBackground()中访问UI的同样问题..我将更新代码..
接近 6 年之前 回复
dongmopu6734
dongmopu6734 result.setText(“签到成功”);
接近 6 年之前 回复
doutang1992
doutang1992 第95行是什么?
接近 6 年之前 回复
doumengwei0138
doumengwei0138 好。 我会尝试。
接近 6 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐