2016-03-07 7 views
0

Привет всем Я пытаюсь получить данные из базы данных MySQL в андроиде ListView,Попытки получить данные MySQL в андроиде ListView

После кода бросает java.lang.StringIndexOutOfBoundsException

Я новичок в развитие Android, если кто-то может направлять меня через это будет очень полезно. Спасибо.

 import java.io.BufferedReader; 
    import java.io.InputStreamReader; 
    import java.io.InputStream; 
    import java.util.ArrayList; 
    import android.app.Activity; 
    import android.app.ProgressDialog; 
    import android.os.Bundle; 
    import android.util.Log; 
    import android.widget.ListView; 
    import org.apache.http.HttpEntity; 
    import org.apache.http.HttpResponse; 
    import org.apache.http.client.HttpClient; 
    import org.apache.http.client.methods.HttpPost; 
    import org.apache.http.impl.client.DefaultHttpClient; 
    import org.json.JSONArray; 
    import org.json.JSONObject; 
    import android.os.AsyncTask; 

public class Main_catagory_one extends Activity{ 
    Activity context; 
      HttpPost httppost; 
      StringBuffer buffer; 
      HttpResponse response; 
      HttpClient httpclient; 
      ProgressDialog pd; 
      CustomAdapter adapter; 
      ListView listProduct; 
      ArrayList<Product> records; 

      protected void onCreate(Bundle savedInstanceState) { 

      //TODO Auto-generated method stub 

      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_main1); 

      context=this; 

      records=new ArrayList<Product>(); 

      listProduct=(ListView)findViewById(R.id.listView1); 

      adapter=new CustomAdapter(context, R.layout.list_view,R.id.textView3, 
      records); 

      listProduct.setAdapter(adapter); 

      } 

      public void onStart(){ 

      super.onStart(); 

      //execute background task 

      BackTask bt=new BackTask(); 

      bt.execute(); 

      } 

      //background process to make a request to server and list product information 

      private class BackTask extends AsyncTask<Void,Void,Void>{ 

      protected void onPreExecute(){ 

      super.onPreExecute(); 

      pd = new ProgressDialog(context); 

      pd.setTitle("Retrieving data"); 

      pd.setMessage("Please wait."); 

      pd.setCancelable(true); 

      pd.setIndeterminate(true); 

      pd.show(); 

      } 

      protected Void doInBackground(Void...params){ 

      InputStream is=null; 

      String result=""; 

      try{ 

        httpclient=new DefaultHttpClient(); 

        httppost= new HttpPost("http://10.0.2.2/fetch_item/getproducts.php"); 

        response=httpclient.execute(httppost); 

        HttpEntity entity = response.getEntity(); 

        // Get our response as a String. 

        is = entity.getContent(); 



       }catch(Exception e){ 

         if(pd!=null) 

         pd.dismiss(); //close the dialog if error occurs 

         Log.e("ERROR", e.getMessage()); 

       } 



      //convert response to string 

      try{ 

      BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),8); 

      StringBuilder sb = new StringBuilder(); 

      String line = null; 

      while ((line = reader.readLine()) != null) { 

      sb.append(line+"\n"); 

      } 

      is.close(); 

      result=sb.toString(); 

      }catch(Exception e){ 

      Log.e("ERROR", "Error converting result "+e.toString()); 



      } 



      //parse json data 

      try{ 

      // Remove unexpected characters that might be added to beginning of the string 

      result=result.substring(result.indexOf("[")); 

      JSONArray jArray =new JSONArray(result); 

      for(int i=0;i<jArray.length();i++){ 

      JSONObject json_data =jArray.getJSONObject(i); 

      Product p=new Product(); 

      p.setpName(json_data.getString("Item_name")); 

      p.setuPrice(json_data.getString("Item_price")); 

      p.setpQauntity(json_data.getString("Item_quantity")); 

      p.setpImage(json_data.getString("Item_img")); 

      records.add(p); 

      } 

      } 

      catch(Exception e){ 

      Log.e("ERROR", "Error pasting data "+e.toString()); 
      } 

      return null; 

      } 

      protected void onPostExecute(Void result){ 

      if(pd!=null) pd.dismiss(); //close dialog 

      Log.e("size", records.size() + ""); 

      adapter.notifyDataSetChanged(); //notify the ListView to get new records 

      } 

      } 

      } 
+0

пожалуйста, вы можете опубликовать содержание результата, прежде чем зачистки его по «[» и если его надлежащему ответу тогда, если открывающий тег «[» существует, должно быть закрывающий тег " ] "также в ответ. Вы гарантированно вытащили «[» от ответа вы удалили «]» также ???? –

+0

result = result.substring (result.indexOf ("[")); Уверен, что indexOf возвращает -1, потому что нет [найдено в строке –

+0

Опубликовать исходную переменную 'result'. – RafaelC

ответ

0

IndexOutOfBoundsException - если beginIndex отрицателен или больше, чем длина этой строки объекта.

Вы должны привыкнуть к использованию API. Он рассказывает вам, какие исключения вызывает метод и почему. Попробуйте напечатать длину строки до и после выполнения подстроки. Например ...

String testing = "Hello World"; 
System.out.println("Length of testing = " + testing.length); 
System.out.println("Value of testing = " + testing); 
testing.substring(1,2); 
Смежные вопросы