我尝试使用以下代码将我的Android应用程序中的JSON对象发送到Django。但有一些错误,我的应用程序退出说不幸停止了。
代码:
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
EditText uname, upass;
Button submit;
String name,pass;
public static final String wurl = "http://172.21.1.59:8000/polls/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
uname=(EditText)findViewById(R.id.editusername);
upass=(EditText)findViewById(R.id.editpwd);
submit=(Button)findViewById(R.id.btnSubmit);
submit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
name=uname.getText().toString();
pass=upass.getText().toString();
JSONObject obj = new JSONObject();
try
{
obj.put("Name", name);
obj.put("Password", pass);
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
HttpClient httpclient = new DefaultHttpClient(myParams );
try {
HttpPost httppost = new HttpPost(wurl.toString());
httppost.setHeader("Content-type", "application/json");
StringEntity se = new StringEntity(obj.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
Log.i("tag", temp);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_login, container, false);
return rootView;
}
}
}
应用程序在运行行时退出" HttpResponse response = httpclient.execute(httppost);"。
有人请帮我解决这个问题。谢谢。
答案 0 :(得分:1)
在Android中,不允许在主线程上运行网络任务。您应该使用AsyncTask。
http://developer.android.com/reference/android/os/AsyncTask.html