我的片段
public class UsuarioFragment extends Fragment {
JSONObject usuario;
View v;
String nombreUsuario;
String emailUsuario;
String tipoUsuario;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.activity_usuario_fragment, container, false);
//Code connection APi localhost...
return v;
}
}
我如何连接到localhost(我使用WAMP)API
AsyncHttpClient client = new AsyncHttpClient();
client.setMaxRetriesAndTimeout(0,10000);
String Url ="http://192.168.126.1/apimyteam/public/api/usuario/2";
client.get(this,Url, new AsyncHttpResponseHandler() {
public void onStart() {
Snackbar.make(getActivity().findViewById(android.R.id.content), "Descargando usuario...", Snackbar.LENGTH_LONG)
.show();
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//public void onSuccess(String content) {
JSONObject cliente = null;
String str = new String(responseBody);
try {
cliente = new JSONObject(str);
} catch (JSONException e) {
e.printStackTrace();
}
try {
nombreUsuario=cliente.getString("uNombre");
emailUsuario=cliente.getString("uEmail");
tipoUsuario=cliente.getString("uTipo");
TextView usuario= (TextView) v.findViewById(R.id.textUsuario);
TextView email= (TextView) v.findViewById(R.id.textEmail);
TextView tipo= (TextView) v.findViewById(R.id.textTipo);
usuario.setText(nombreUsuario);
email.setText(emailUsuario);
tipo.setText(tipoUsuario);
} catch (JSONException e) {
Snackbar.make(getActivity().findViewById(android.R.id.content), "Se ha producido un error con el usuario...", Snackbar.LENGTH_LONG)
.show();
return;
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
String str = new String(error.getMessage().toString());
String valor = "No se ha podido recuperar los datos desde el servidor. " + str;
Snackbar.make(getActivity().findViewById(android.R.id.content), valor, Snackbar.LENGTH_LONG)
.show();
}
});
错误:
无法解决方法' get(com.example.roberto.androidprototipofinal.UsuarioFragment,java.lang.String,anonymous com.loopj.android.http.AsyncHttpResponseHandle)'
我尝试使用getContext()或getActivty()来解决这个问题,但它仍然没有工作......
答案 0 :(得分:1)
由于您位于Fragment
,因此您需要将this
更改为getActivity()
,这样才能解决问题
无法解析方法'get(com.example.roberto.androidprototipofinal.UsuarioFragment,java.lang.String,anonymous com.loopj.android.http.AsyncHttpResponseHandle)'
Okey但现在它说:“权限被拒绝”
然后你必须在manifest.xml
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET" />
<application>
....
</application>
</manifest>