Java 如何优化android代码
我有这个代码,这是正确的编写方法吗,还是我需要遵循任何编码模式或标准 请给我一些建议,因为我不喜欢Android编码 更新:Java 如何优化android代码,java,android,coding-style,standards,Java,Android,Coding Style,Standards,我有这个代码,这是正确的编写方法吗,还是我需要遵循任何编码模式或标准 请给我一些建议,因为我不喜欢Android编码 更新: public String getBrotherHood() throws Exception{ client = new DefaultHttpClient(); get = new HttpGet(uri); res = client.execute(get); sl = res.getStatusLine();
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();
}
}
公共类JSONData{
public ArrayList getBrotherhoodyJSON()抛出JSONException、IOException、Exception{
ArrayList项=新建ArrayList();
JSONArray jA=新的JSONArray(getBrotherHood());
对于(inti=0;i,eclipse提供了一个默认的代码格式化程序。编写代码后,只需键入“Control+Shift+F”。您的android代码将自动格式化。您显然已在方法之外声明了所有变量,即使它们似乎仅在该方法中使用。这毫无意义。它可以防止多个对象被垃圾收集。您最好将声明移到该方法中
声明抛出异常
也没有多大意义。如果您声明一个可能发生的特定异常,或者将所有不太可能发生的异常转换为RuntimeException
,那么您就不需要声明它们了。还有一点很重要,那就是重新格式化readBuffer Variable
在函数的最后一个部分,您返回readBuffer.toString(),并且只有在状态为200时才初始化它。但是如果状态为非200,则它将为null(假设as声明不可见),因此为null.toString()will Thinked exception.查看此部分了解一些约定提示,不要捕获所有异常异常e
。只捕获异常
该方法可以抛出的异常这是一条很好的信息:)当然,我会按照您提到的内容进行操作。谢谢:)
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;
}