2015-11-04 54 views
0

enter image description here我用Asp.net MVC创建一个API,它返回JSON。现在我想在我的Android应用程序中接收JSON,但它有错误。如何获取Json在android

我返回[{"id":22,"Name":"2","Family":"1"}],我的浏览器显示在http://192.168.1.100/api/people

这里是我的Android代码:

public class ReteriveFormWebActivity extends Activity { 

    private static String  url  = "http://192.168.1.100/api/people"; 

    //JSON Node Names 


    JSONArray     user  = null; 


    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams()); 
     HttpPost httppost = new HttpPost(url); 
     // Depends on your web service 
     httppost.setHeader("Content-type", "application/json"); 

     InputStream inputStream = null; 
     String result = null; 
     try { 
      HttpResponse response = httpclient.execute(httppost); 
      HttpEntity entity = response.getEntity(); 

      inputStream = entity.getContent(); 
      // json is UTF-8 by default 
      BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8); 
      StringBuilder sb = new StringBuilder(); 

      String line = null; 
      while ((line = reader.readLine()) != null) 
      { 
       sb.append(line + "\n"); 
      } 
      result = sb.toString(); 
      Log.i("re", result); 
     } 
     catch (Exception e) { 
      // Oops 
     } finally { 
      try { 
       if (inputStream != null) 
        inputStream.close(); 
      } 
      catch (Exception squish) {} 
     } 
    } 
} 

在日志中显示错误eccurred:为什么呢?

+1

'在日志中显示错误eccurred'哪个错误?显示应用程序崩溃时的logcat结果 –

+0

请有人帮我 – aliyousefian

+0

在日志中显示错误eccurred哪个错误?显示应用程序崩溃时的logcat结果 –

回答

0

获取NPE由于:

.... 
TextView txts = (TextView) findViewById(R.id.txt); 
txts.setText(result); //<<<< 
.... 

线造成的问题,因为txtsnull

为什么null

因为没有要求通过传递布局ID中的TextView与txtonCreate提供setContentView方法。

做得一样:

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_layout_file_name); 
    ... your code here 
} 

注: Currenlty做在主UI线程与网络有关的任务,这将导致ANR对话框。因此在后台线程中使用AsyncTask做网络相关的作业。

+0

这不是答案我现在用我的textview和log.i如何一个错误消息发生我的问题是得到JSON不是UI setContentView(R.layout.activity_layout_file_name); – aliyousefian

+0

@ user3480060:伙计。如果你评论这个Log.i(“resss”,e.toString());'line,那么你仍然会遇到问题,因为由于'txts'为'null',程序将进入catch catch try/catch块。如果你知道什么是问题,那么为什么不修理它而不是提问呢? –

+0

对不起,先生。但我删除所有textview如果JSON张贴在logcat中必须显示我的JSON,但显示一个错误ECACTRE为什么? – aliyousefian

0

将所有httprequests放入新线程中。您不能在ui线程中执行httprequests。