如何在不点击按钮的情况下自动从MySQL到Android获取数据?

时间:2016-05-31 01:56:23

标签: mysql json button barcode android-studio-2.0

我希望条形码扫描的结果能够自动从MySQL获取数据,而无需再次单击按钮。

这是我点击按钮以从MySQL获取数据的代码。如何在不再次单击按钮的情况下获取相同的数据?

public class EditPerangkat extends AppCompatActivity implements View.OnClickListener {

private EditText editTextNoIT;
private Button buttonGet;
private TextView textViewResult;

private ProgressDialog loading;

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

    Scan = (Button) findViewById(R.id.buttonScan);
    buttonGet = (Button) findViewById(R.id.buttonGet);
    textViewResult = (TextView) findViewById(R.id.textViewResult);

    Scan.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            IntentIntegrator scanIntegrator = new IntentIntegrator(EditPerangkat.this);
            scanIntegrator.initiateScan();
        }
    });

    buttonGet.setOnClickListener(this);
}

private void getData() {
    String it = editTextNoIT.getText().toString().trim();
    if (it.equals("")) {
        Toast.makeText(this, "Please input data", Toast.LENGTH_LONG).show();
        return;
    }
    loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);

    String url = Config.URL_GET+editTextNoIT.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(EditPerangkat.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
                }
            });

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}

public void showJSON(String response){
    String jenisperangkat="";
    String namaperangkat="";
    String serialnumber= "";
    try {
        JSONObject jsonObject = new JSONObject(response);
        JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);
        JSONObject collegeData = result.getJSONObject(0);
        jenisperangkat = collegeData.getString(Config.KEY_PER_JENISPERANGKAT);
        namaperangkat = collegeData.getString(Config.KEY_PER_NAMAPERANGKAT);
        serialnumber = collegeData.getString(Config.KEY_PER_SERIALNUMBER);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    textViewResult.setText(jenisperangkat + "\n" + namaperangkat + "\n" + serialnumber);
}

@Override
public void onClick(View v) {
    getData();
}

1 个答案:

答案 0 :(得分:0)

你的IntentIntegrator类应该给出一些回调/监听器事件。  扫描完成后,将触发回调/事件,您可以调用getdata()。