2012-05-11 54 views
0

这里是我的课,我尝试从JSONArray中使用JSON进入JSONArray一些数据。来自JSON的数据MYSQL

它在屏幕上显示两个Toast:NullPointerEception和另一个异常,它将所有我在php网页中所写的所有内容逐字写入。

public class ConnectMySql extends Activity{ 
InputStream is; 
//List<String> items; 
JSONArray jArray; 
//String[] items; 
StringBuilder sb; 
//ListView list; 
TextView textv; 
    String result; 
//List<NameValuePair> items; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
//list = (ListView) findViewById(R.id.listview); 

textv = (TextView) findViewById(R.id.tvHI); 
setContentView(R.layout.main); 

try{ 
    HttpClient httpsClient = new DefaultHttpClient(); 
    HttpPost httpPost = new HttpPost("http://79.114.48.119/data.php"); 

    List<NameValuePair> nameValue = new ArrayList<NameValuePair>(); 
    httpPost.setEntity(new UrlEncodedFormEntity(nameValue)); 
    HttpResponse httpResponse = httpsClient.execute(httpPost); 
    HttpEntity httpEntity = httpResponse.getEntity(); 
    is = httpEntity.getContent(); 
}catch(Exception e){ 
    Log.e("log_tag", "Error in HTTP connection" + e.toString()); 
    Toast.makeText(this, "http connection error: " + e.toString(), Toast.LENGTH_LONG).show(); 
} 
    try{ 
     BufferedReader BufR = new BufferedReader (new InputStreamReader(is, "iso-8859-1"),8); 
     sb = new StringBuilder(); 
     sb.append(BufR.readLine() + "\n"); 
     String line = "0"; 

     while((line = BufR.readLine()) != null){ 
      sb.append(line + "\n"); 
     } 
     is.close(); 
     result = sb.toString(); 
    }catch(Exception e){ 
     Log.e("log_tag", "Error in convert String" + e.toString()); 
    } 
    int lat; 
    int lon; 
    try{ 
     jArray = new JSONArray(result); 
     Toast.makeText(this, "no data found" + result, Toast.LENGTH_LONG).show(); 
     JSONObject json_data = null; 
     for(int i = 0; i< jArray.length(); i++){ 
      json_data = jArray.getJSONObject(i); 
      lat = json_data.getInt("latitude"); 
      lon = json_data.getInt("longitude"); 

      textv.setText(lat + lon); 

      //Here i use another function whitch uses lat & lon 
     } 
     //setupList(); 
    }catch(JSONException e){ 
     Toast.makeText(this, "no data found", Toast.LENGTH_LONG).show(); 
    }catch(Exception e){ 
     Toast.makeText(this, "error" + e.toString(), Toast.LENGTH_LONG).show(); 
    } 
} 
} 
/*private void setupList() { 

// TODO Auto-generated method stub 
list.setAdapter(new ArrayAdapter<String>(this, 
     android.R.layout.simple_list_item_1, items)); 
} 

}*/ 

你能帮我吗?非常感谢你 !

+0

Post full stacktrace。 – kosa

回答

1

几次失误在你的代码:

1)的setContentView()必须findViewById(),或使用XML布局引用任何其他方法之前调用。

2)你想在UI线程上执行网络操作(HTTP请求必须从另一个线程来执行 - 否则 - 它抛出的异常)

不要忘记添加到您的清单上网权限忘了或不知道你需要

+0

我之前打过setcontentview,但能否向我解释第二点。我真的不知道你在说什么。谢谢。 –

+0

我打电话给setcontentview,但textview仍然没有改变。你能解释我更好的数字2吗?我真的不明白你的意思。非常感谢你 ! –

+0

没有人知道:(? –