public String getBrotherHood() throws Exception{
client = new DefaultHttpClient();
get = new HttpGet(uri);
res = client.execute(get);
sl = res.getStatusLine();
sCode = sl.getStatusCode();
if(sCode==200)
{
try{
reader = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
readBuffer = new StringBuffer();
while((nl = reader.readLine())!=null){
readBuffer.append(nl);
}
reader.close();
}finally{
if(reader !=null)
{
try{
reader.close();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
return readBuffer.toString();
}
}
我有這段代碼,這是寫它的正確方式,還是我需要遵循任何編碼模式或標準?如何優化android代碼
請給我一些建議,因爲我沒有給Android編碼。
更新:
public class JSONData {
public ArrayList<String> getBrotherHoodJSON() throws JSONException,IOException,Exception{
ArrayList<String> item = new ArrayList<String>();
JSONArray jA = new JSONArray(getBrotherHood());
for(int i=0; i<jA.length(); i++)
{
JSONObject jO = jA.getJSONObject(i);
String n = jO.getString("name");
item.add(n);
Log.i("JsonData:",jO.getString("name"));
}
return item;
}
public String getBrotherHood() throws Exception{
BufferedReader in = null;
String data= null;
HttpClient client = new DefaultHttpClient();
URI uri = new URI("http://fahidmohammad.in/demo/Android/api.php?user=fah");
HttpGet get = new HttpGet();
get.setURI(uri);
HttpResponse res = client.execute(get);
StatusLine sl = res.getStatusLine();
int sCode = sl.getStatusCode();
if(sCode==200)
{
try{
in = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
StringBuffer sb = new StringBuffer();
String nl;
while((nl = in.readLine())!=null){
sb.append(nl);
}
in.close();
data = sb.toString();
Log.i("Raw Data:",data);
return data;
}finally{
if(in !=null)
{
try{
in.close();
return data;
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
return data;
}
這裏是更新的版本相同的代碼。照顧所有提到的問題。
而且它的工作就像一個魅力,但不知道它的穩定性。
看看這個一些約定的提示,http://source.android.com/source/code-style.html – Austin
不要捕獲所有異常'異常e'。只捕獲那個方法可能拋出的'Exceptions' – alaster