如何使用asynctask从数据库mysql中获取数据?

时间:2016-10-21 08:07:28

标签: android json android-asynctask

TextView中获取数据时,我收到错误消息。我试过但它不起作用。 my output image

  

解析数据时出错org.json.JSONException:字符0处的输入结束

的Json

  [{
    "0": "1",
    "cl_id": "1",
    "1": "",
    "cl_department": "",
    "2": "3G COMMUNICATION",
    "cl_pname": "3G COMMUNICATION",
    "3": "NIRAJBHAI",
    "cl_salesperson": "NIRAJBHAI",
    "4": "",
    "cl_oname": "",
    "5": "MOHMADBHAI",
    "cl_contact": "MOHMADBHAI",
    "6": "JUBELY SHAK MARKET",
    "cl_address": "JUBELY SHAK MARKET",
    "7": "",
    "cl_city": "",
    "8": "360001",
    "cl_pincode": "360001",
    "9": "",
    "cl_bdate": "",
    "10": "",
    "cl_adate": "",
    "11": "",
    "cl_opening": "",
    "12": "9376052000",
    "cl_cnumber": "9376052000",
    "13": "",
    "cl_wnumber": "",
    "14": "",
    "cl_email": "",
    "15": "RT40848",
    "cl_wodcode": "RT40848",
    "16": "",
    "cl_active": "",
    "17": "",
    "cl_saleman": "",
    "18": "",
    "cl_bank_name": "",
    "19": "",
    "cl_bank_city": "",
    "20": "",
    "cl_ifsc_code": "",
    "21": "",
    "cl_bank_ac_no": "",
    "22": "",
    "cl_bank_ac_holder": "",
    "23": "",
    "cl_pancard_no": "",
    "24": "",
    "cl_visiting_card": "",
    "25": "ACTIVE",
    "cl_status": "ACTIVE",
    "26": "",
    "cl_aread": "",
    "27": "",
    "cl_target": "",
    "28": "",
    "cl_archive": "",
    "29": "",
    "cl_remaining": "",
    "30": "A1",
    "cl_group": "A1",
    "31": "Om",
    "cl_category": "Om",
    "32": "",
    "cl_credit": ""
},

这是我的完整代码,

Main.java

public class MainActivity extends Activity {

    private WebView wv1;
    InputStream is=null;
    String result=null;
    String line=null;
    JSONObject jsonobject;
    public static String DATA_URL = "http://10.0.2.2/portal/fetchwod.php";
    JSONParser jParser = new JSONParser();
    JSONArray ownerObj;
    ArrayList<HashMap<String, String>> arraylist;
    ArrayList<String> delivery_fetch = new ArrayList<String>();
    String suid,uid,wt_wod_code1,wt_party1;
    TextView abcd,abc1;
    View view;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        new DownloadJSON().execute();
        abcd =(TextView)findViewById(R.id.abc);
        abc1 =(TextView)findViewById(R.id.abc1);
    }

    private class MyBrowser extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url ) {
            view.loadUrl(url);
        String id = abcd.getText().toString().trim();
            return true;
        }
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        return super.onOptionsItemSelected(item);
    }

    private class DownloadJSON extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected Void doInBackground(Void... voids) {

            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost("http://10.0.2.2/portal/autocomplete.php");
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
                Log.e("Pass 1", "connection success ");
            } catch (Exception e) {
                Log.e("Fail 1", e.toString());
                Toast.makeText(getApplicationContext(), "Invalid IP Address", Toast.LENGTH_LONG).show();
            }
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();
                Log.e("Pass 2", "connection success ");
            } catch (Exception e) {
                Log.e("Fail 2", e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            try {
                JSONArray JA = new JSONArray(result);
                JSONObject json = null;
                final String[] str1 = new String[JA.length()];

                for (int i = 0; i < JA.length(); i++) {
                    json = JA.getJSONObject(i);
                    str1[i] = json.getString("cl_pname");
                }
                final AutoCompleteTextView text = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
                final List<String> list = new ArrayList<String>();

                for (int i = 0; i < str1.length; i++) {
                    list.add(str1[i]);
                }

                Collections.sort(list);
                final ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.my_list_item, list);
                dataAdapter.setDropDownViewResource(android.R.layout.simple_list_item_1);
                text.setThreshold(1);
                text.setAdapter(dataAdapter);
                text.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                        wv1 = (WebView) findViewById(R.id.webView);
                        wv1.setWebViewClient(new MyBrowser());
                        wv1.loadUrl("http://10.0.2.2/portal/on_target.php?=cod");
                        wv1.getSettings().setLoadsImagesAutomatically(true);
                        wv1.getSettings().setJavaScriptEnabled(true);
                        wv1.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
                        Toast.makeText(getApplicationContext(), (CharSequence) arg0.getItemAtPosition(arg2), Toast.LENGTH_LONG).show();
                        wt_wod_code1 = text.getText().toString();
                        wt_party1 = text.getText().toString();
                        abcd.setText(text.getText());
                        Log.d("wt_wod_code", wt_party1);
                        new getdata().execute();

                    }
                });
            } catch (Exception e) {
                Log.e("Fail 3", e.toString());
            }
        }
    }
    private class getdata extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... voids) {
            try {
                String uid = abcd.getText().toString().trim();
                arraylist = new ArrayList<HashMap<String, String>>();

                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("cl_pname", uid));
                JSONObject json = jParser.makeHttpRequest(DATA_URL, "GET", params);

                int success1 = Integer.parseInt(json.getString("success4"));
                Log.d("success4", json.toString());

                if (success1 == 0) {
                    Snackbar.make(view, "Not Data Found", Snackbar.LENGTH_LONG).show();
                }
                if (success1 == 1) {
                    ownerObj = json.getJSONArray("Ordera");
                    for (int i = 0; i < ownerObj.length(); i++) {
                        jsonobject = ownerObj.getJSONObject(i);
                        delivery_fetch.add(jsonobject.getString("cl_wodcode"));
                    }
                }
            }
            catch(Exception e)
            {
            }
            return null;
        }
        @Override
        protected void onPostExecute(Void args) {
            abc1 =(TextView)findViewById(R.id.abc1);
            abc1.setText(delivery_fetch.toString());
        }

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;

    }
}

这是我的Logcat,

com.example.sachin.addvisit E/Pass 1: connection success 
com.example.sachin.addvisit E/Pass 2: connection success 
com.example.sachin.addvisit D/wt_wod_code: D.K. METAL
com.example.sachin.addvisit D/response: {"success":1,"Ordera":[{"cl_wodcode":"RT34705","cl_pname":"D.K. METAL"}]}
com.example.sachin.addvisit E/Buffer Error: Error converting result java.lang.NullPointerException: lock == null
com.example.sachin.addvisit E/JSON Parser: Error parsing data org.json.JSONException: End of input at character 0 of 

数据显示在logcat中,但未在TextView中提取。

我在网上验证了我的JSON,看起来没问题。

我不知道问题出在哪里,请帮助我。

如果需要,我也会发布 API ..

1 个答案:

答案 0 :(得分:0)

按如下方式解析JSON

final String[] str1 = new String[JA.length()];
final String[] str2 = new String[JA.length()];

for (int i = 0; i < JA.length(); i++) {
    json = JA.getJSONObject(i);
    str1[i] = json.getString("cl_pname");
    str2[i] = json.getString("cl_wodcode");
}

OnItemClickListener内,

text.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        String selected_cl_pname = (String) parent.getItemAtPosition(position);
        int index = Arrays.asList(str1).indexOf(selected_cl_pname);

        String selected_cl_wodcode = str2[index];
        abc1.setText(selected_cl_wodcode);

        // rest of your code
    }
});

我建议使用模型类并使用GSON来解析JSON