Android 将数据发送到“片段”选项卡下的服务器
我真的是个编程新手。我正在做一个有标签的应用程序,每个标签都是一个片段,在这个标签中,我想向服务器发送一些数据。下面是代码,看起来所有的get()something函数都不在片段下工作。(我已经解决了这个问题)现在程序无法运行 这是我的密码Android 将数据发送到“片段”选项卡下的服务器,android,android-fragments,android-json,Android,Android Fragments,Android Json,我真的是个编程新手。我正在做一个有标签的应用程序,每个标签都是一个片段,在这个标签中,我想向服务器发送一些数据。下面是代码,看起来所有的get()something函数都不在片段下工作。(我已经解决了这个问题)现在程序无法运行 这是我的密码 public class TabActivityMain extends Fragment implements OnClickListener { TextView tvIsConnected; EditText etName,etCountry,etT
public class TabActivityMain extends Fragment implements OnClickListener {
TextView tvIsConnected;
EditText etName,etCountry,etTwitter;
Button btnPost;
Person person;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View V = inflater.inflate(R.layout.activity_tab_activity_main, container, false);
tvIsConnected = (TextView) V.findViewById(R.id.tvIsConnected);
etName = (EditText) V.findViewById(R.id.etName);
etCountry = (EditText) V.findViewById(R.id.etCountry);
etTwitter = (EditText) V.findViewById(R.id.etTwitter);
btnPost = (Button) V.findViewById(R.id.btnPost);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
}
else{
tvIsConnected.setText("You are NOT conncted");
}
// add click listener to Button "POST"
btnPost.setOnClickListener(this);
return V;
}
public static String POST(String url, Person person){
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name", person.getName());
jsonObject.accumulate("country", person.getCountry());
jsonObject.accumulate("twitter", person.getTwitter());
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// ** Alternative way to convert Person object to JSON string usin Jackson Lib
// ObjectMapper mapper = new ObjectMapper();
// json = mapper.writeValueAsString(person);
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
@Override
public void onClick(View view) {
switch(view.getId()){
case R.id.btnPost:
if(!validate())
Toast.makeText(getActivity().getBaseContext(), "Enter some data!", Toast.LENGTH_LONG).show();
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");
break;
}
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
person = new Person();
person.setName(etName.getText().toString());
person.setCountry(etCountry.getText().toString());
person.setTwitter(etTwitter.getText().toString());
return POST(urls[0],person);
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
Toast.makeText(getActivity().getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
}
}
private boolean validate(){
if(etName.getText().toString().trim().equals(""))
return false;
else if(etCountry.getText().toString().trim().equals(""))
return false;
else if(etTwitter.getText().toString().trim().equals(""))
return false;
else
return true;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
必须位于函数的末尾,因为返回总是会退出函数并停止编译其余代码。至于你的日志:添加
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
就在AndroidManifest.xml文件中的应用程序标记上方。由于您不再处于活动中,您需要为大多数函数设置上下文 例如,findViewByID需要知道在哪个视图中查看 因此,在您的示例中,您将使用
V.findViewByID(..)
虽然通常使用getView().findViewByID
在另一种情况下,你会寻找
getActivity().getSystemService
以下是获取上下文的不同方法的一个很好的解释:
通常,onCreateView的外观如下所示:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_tab_activity_main, container, false);
}
然后将onCreateView中的其余代码移动到onActivityCreated
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//...more code goes here and you can easily just do getView().findViewByID
}
要知道你的回报是V;这叫提前返程。一旦一个方法命中一个return语句,它就会这样做,而该方法中的其余代码就“死了”
此外,您不应该在异步任务中访问UI线程。AsyncTask正在打开一个新线程,并且不一定具有对UI的访问权限。因此,您应该将包含所有人员详细信息的对象传递到AsyncTask中
最后一件事,这是偏好或风格,我相信人们会不同意。我想说,作为一个新手,避免使用没有花括号的if和while语句是一个好习惯:
坏的:
相反,你应该用括号表示:
好:
祝你好运 另外,使用Json向web服务器发送数据的代码是否有任何错误;使用
getActivity()
应该是onCreateView()的最后一条语句,它在我在menifest中添加权限后工作。但是为什么我不能在编辑文本字段yourEditText.setEditable(true)和yourEditText.setFocusable(true)中键入任何内容必须设置,但默认情况下它们应该为true,因此如果您没有更改,我不明白为什么它不起作用。也许可以为此提出一个新问题,并在那里发布您的xml。
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity_tab_activity_main, container, false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//...more code goes here and you can easily just do getView().findViewByID
}
if(whatever == 1)
//blah blah
if(whatever == 1){
//blah blah
}