Can anybody please help me with this one. I am trying to get information in a server through web API, I believe, in my code below that I can already connect to the server (because no error appear). But when I am trying to display information that that I get, it display null value. I'm not sure where a forgot something or if my way of parsing it is right.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonGetData = (Button) findViewById(R.id.buttonGetData);
editTextSearchString = (EditText) findViewById(R.id.editTextSearchString);
textViewFirstName = (TextView) findViewById(R.id.textViewFirstName);
textViewLastName = (TextView) findViewById(R.id.textViewLastName);
display = (TextView) findViewById(R.id.display);
spn_Display = (Spinner)findViewById(R.id.spn_Display);
//Setup the Button's OnClickListener
buttonGetData.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Get the data
in = null;
DoPOST mDoPOST = new DoPOST(MainActivity.this, editTextSearchString.getText().toString());
Toast.makeText(getApplicationContext(), editTextSearchString.getText().toString(), 6).show();
mDoPOST.execute("");
buttonGetData.setEnabled(false);
}
});
}
public class DoPOST extends AsyncTask<String, Void, Boolean>
{
Context mContext = null;
String strNameToSearch = "";
//Result data
String strFirstName;
String strLastName;
int intAge;
int intPoints;
Exception exception = null;
DoPOST(Context context, String nameToSearch){
mContext = context;
strNameToSearch = nameToSearch;
}
#Override
protected Boolean doInBackground(String... arg0) {
try{
//Setup the parameters
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Username", "admin"));
nameValuePairs.add(new BasicNameValuePair("Password", "admin123"));
//Create the HTTP request
HttpParams httpParameters = new BasicHttpParams();
//Setup timeouts
HttpConnectionParams.setConnectionTimeout(httpParameters, 15000);
HttpConnectionParams.setSoTimeout(httpParameters, 15000);
HttpClient httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost("http://examplesvr4.sample.com:1217/api/subbrands");
HttpGet httpget = new HttpGet("http://examplesvr4.sample.com:1217/api/subbrands");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
result = EntityUtils.toString(entity);
// Create a JSON object from the request response
JSONObject jsonObject = new JSONObject(result);
//Retrieve the data from the JSON object
strFirstName = jsonObject.getString("SubBrandId");
strLastName = jsonObject.getString("SubBrandName");
}catch (Exception e){
Log.e("ClientServerDemo", "Error:", e);
exception = e;
}
return true;
}
#Override
protected void onPostExecute(Boolean valid){
//Update the UI
textViewFirstName.setText("First Name: " + strFirstName);
textViewLastName.setText("Last Name: " + strLastName);
buttonGetData.setEnabled(true);
if(exception != null){
Toast.makeText(mContext, exception.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
Related
I'm working on an android project and I use JSON to intechange data with server.. Problem is here when I use JSON file with UTF-8 format, some crash happens and the app stops.. and when I don't, it works fine.
I really need to have my files in UTF-8 format to have the correct charecters.
Where am I missing? Thank you in advanced.
Here is my Service Handler class:
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method, List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
and Here is the method I use in main activity:
private class GetContacts extends AsyncTask {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SecondActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = null;
try {
jsonObj = new JSONObject(jsonStr);
} catch (JSONException e) {
e.printStackTrace();
}
// Getting JSON Array node
if (jsonObj != null) {
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
}
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String id = c.getString(TAG_ID);
String title = c.getString(TAG_Title);
String content = c.getString(TAG_CONTENT);
String date = c.getString(TAG_DATE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, id);
contact.put(TAG_Title, title);
contact.put(TAG_CONTENT, content);
contact.put(TAG_DATE, date);
// adding contact to contact list
conatctlist.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
ListView lv = (ListView)findViewById(R.id.listView);
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
SecondActivity.this, contactlist,
R.layout.list_item_2, new String[] { TAG_Title, TAG_CONTENT,
TAG_DATE }, new int[] { R.id.name,
R.id.email, R.id.date });
lv.setAdapter(adapter);
}
}//end getContacts
May be, You have to define HttpClient like this...(Not Tested)
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
params.setBooleanParameter("http.protocol.expect-continue", false);
HttpClient httpclient = new DefaultHttpClient(params);
I am trying to POST data using an http request method from an Android application to a Wamp server.
When I run the application a success message is shown on the Android app, but there is no data inserted in the table of the Wamp server. There is no error shown on logcat. What am I doing wrong?
public class MainActivity extends Activity {
private EditText editTextName;
private EditText editTextAdd;#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextAdd = (EditText) findViewById(R.id.editTextAddress);
}
public void insert(View view) {
String name = editTextName.getText().toString();
String add = editTextAdd.getText().toString();
insertToDatabase(name, add);
}
private void insertToDatabase(String name, String add) {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramAddress = params[1];
String name = editTextName.getText().toString();
String add = editTextAdd.getText().toString();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name", name));
nameValuePairs.add(new BasicNameValuePair("address", add));
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://ip address of my system/Employee3/create_product.php");
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return "success";
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
TextView textViewResult = (TextView) findViewById(R.id.textViewResult);
textViewResult.setText("Inserted");
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(name, add);}
}
For the Http debugging, I suggest you firstly use some tools to test the interface, such as curl or postMan. Make sure the post/get method work correct in these tools, then test the interface in Android
I am trying to create a Login function so i can verify the users. I pass the Username , Password variables to AsyncTask class but i don't know hot to get results in order to use them. Any help? (I am posting part of the source code due to website restrictions)
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(txtUsername.getText().toString().trim().length() > 0 && txtPassword.getText().toString().trim().length() > 0)
{
// Retrieve the text entered from the EditText
String Username = txtUsername.getText().toString();
String Password = txtPassword.getText().toString();
/*Toast.makeText(MainActivity.this,
Username +" + " + Password+" \n Ready for step to post data", Toast.LENGTH_LONG).show();*/
String[] params = {Username, Password};
// we are going to use asynctask to prevent network on main thread exception
new PostDataAsyncTask().execute(params);
// Redirect to dashboard / home screen.
login.dismiss();
}
else
{
Toast.makeText(MainActivity.this,
"Please enter Username and Password", Toast.LENGTH_LONG).show();
}
}
});
Then i use the AsynkTask to do the check but do not know how to get the results and store them in a variable. Any help?
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
// do stuff before posting data
}
#Override
protected String doInBackground(String... params) {
try {
// url where the data will be posted
String postReceiverUrl = "http://server.com/Json/login.php";
Log.v(TAG, "postURL: " + postReceiverUrl);
String line = null;
String fail = "notok";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserName", params[0]));
nameValuePairs.add(new BasicNameValuePair("Password", params[1]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
line = resEntity.toString();
Log.v(TAG, "Testing response: " + line);
if (resEntity != null) {
String responseStr = EntityUtils.toString(resEntity).trim();
Log.v(TAG, "Response: " + responseStr);
Intent Hotels_btn_pressed = new Intent(MainActivity.this, Hotels.class);
startActivity(Hotels_btn_pressed);
// you can add an if statement here and do other actions based on the response
Toast.makeText(MainActivity.this,
"Error! User does not exist", Toast.LENGTH_LONG).show();
}else{
finish();
}
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String lenghtOfFile) {
// do stuff after posting data
}
}
Not the best code refactoring, but just to give you a hint.
I would create an interface (lets call it 'LogInListener'):
public interface LoginListener {
void onSuccessfulLogin(String response);
void onFailedLogin(String response);
}
The 'MainActivity' class would implement that interface and set itself as a listener the 'PostDataAsyncTask'. So, creating the async task from the main activity would look like this:
String[] params = {Username, Password};
// we are going to use asynctask to prevent network on main thread exception
PostDataAsyncTask postTask = new PostDataAsyncTask(this);
postTask.execute(params);
I would move 'PostDataAsyncTask' class into a new file:
public class PostDataAsyncTask extends AsyncTask<String, String, String> {
private static final String ERROR_RESPONSE = "notok";
private LoginListener listener = null;
public PostDataAsyncTask(LoginListener listener) {
this.listener = listener;
}
#Override
protected String doInBackground(String... params) {
String postResponse = "";
try {
// url where the data will be posted
String postReceiverUrl = "http://server.com/Json/login.php";
// HttpClient
HttpClient httpClient = new DefaultHttpClient();
// post header
HttpPost httpPost = new HttpPost(postReceiverUrl);
// add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserName", params[0]));
nameValuePairs.add(new BasicNameValuePair("Password", params[1]));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// execute HTTP post request
HttpResponse response = httpClient.execute(httpPost);
HttpEntity resEntity = response.getEntity();
postResponse = EntityUtils.toString(resEntity).trim();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return postResponse;
}
#Override
protected void onPostExecute(String postResponse) {
if (postResponse.isEmpty() || postResponse.equals(ERROR_RESPONSE) ) {
listener.onFailedLogin(postResponse);
} else {
listener.onSuccessfulLogin(postResponse);
}
}
}
So, 'doInBackground' returns the response to 'onPostExecute' (which runs on the UI thread), and 'onPostExecute' routes the result (success or failure) to the MainActivity, which implements the 'LogInListener' methods:
#Override
public void onSuccessfulLogin(String response) {
// you have access to the ui thread here - do whatever you want on suscess
// I'm just assuming that you'd like to start that activity
Intent Hotels_btn_pressed = new Intent(this, Hotels.class);
startActivity(Hotels_btn_pressed);
}
#Override
public void onFailedLogin(String response) {
Toast.makeText(MainActivity.this,
"Error! User does not exist", Toast.LENGTH_LONG).show();
}
I just assumed that that's what you wanted to do on success: start a new activity, and show a toast on fail.
im trying to send my json object to a server addres, but it doesnt let me do it, gives me an error on the execute method, i have tried with all the answers regarding this issue on this forum and still can not make it work, what do you think is my mistake?
here is the code
public class MainActivity extends Activity implements OnClickListener{
Button btnLogin, btnRegister;
EditText tvEmail, tvPassword;
TextView tvResultJson1;
Gson g;
AsyncHttpClient client;
Usuario usuario;
public String url = "http://unshakable-kingswood-61-157350.use1-2.nitrousbox.com:9000/login";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainlogin);
btnLogin =(Button)findViewById(R.id.btnLogin);
btnRegister=(Button)findViewById(R.id.btnRegister);
tvEmail=(EditText)findViewById(R.id.tvEmail);
tvPassword=(EditText)findViewById(R.id.tvPassword);
tvResultJson1=(TextView)findViewById(R.id.tvResultJson1);
client= new AsyncHttpClient();
g= new Gson();
btnRegister.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Intent i= new Intent(MainActivity.this, RegisterForm.class);
//startActivity(i);
}
});
// check if you are connected or not
if(isConnected()){
}
else{
Toast toast1 =
Toast.makeText(getApplicationContext(),
"there is no internet access", Toast.LENGTH_SHORT);
toast1.show();
finish();
}
btnLogin.setOnClickListener((OnClickListener) this);
}
private boolean isConnected() {
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
return true;
else
return false;
}
public void onClick(View view) {
// Get user defined values
sendData();
}
private void sendData() {
String json="";
Usuario usuario = new Usuario();
usuario.setMail(tvEmail.getText().toString());
usuario.setPass(tvPassword.getText().toString());
JsonObject jsonObject= new JsonObject();
jsonObject.addProperty("mail", usuario.getNombre());
jsonObject.addProperty("pass", usuario.getPass());
json = jsonObject.toString();
UploadASyncTask upload = new UploadASyncTask();
upload.execute(jsonObject);
}
private class UploadASyncTask extends AsyncTask<JSONObject, Void, Void>{
#Override
protected Void doInBackground(JSONObject...jsonObject) {
try{
HttpParams params = new BasicHttpParams();
//params.setParameter("data", auth);
HttpClient httpclient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost("http://unshakable-kingswood-61-157350.use1-2.nitrousbox.com:9000/login");
List<NameValuePair> postParams = new ArrayList<NameValuePair>();
postParams.add(new BasicNameValuePair("data", jsonObject.toString()));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParams);
entity.setContentEncoding(HTTP.UTF_8);
httpPost.setEntity(entity);
HttpResponse httpResponse = httpclient.execute(httpPost);
InputStream inputStream = httpResponse.getEntity().getContent();
String result = "";
if(inputStream != null){
result="Si funciono";
}
else{
result = "Did not work!";
}
Log.d("RESULT", result);
}catch(Exception e){
Log.e("ERROR IN SEVER UPLOAD", e.getMessage());
}
return null;
}
}
}
You have mixed up your imports.
in sendData() you are using a JsonObject - note the camel case
in your AsyncTask you are using a JSONObject - note JSON is all in capitals.
Am new to android and developing an android app that posts a search item (which is supplied by user into an EditText) to the server when a button is clicked,the item is posted to the server.Am using Asynctask class.I have error with the findViewById(it is undefined).My problem is where to place the onclick method and referncing of the views.Here is the code
public class Server_Post extends AsyncTask<String, Void, String> {
private static final int REGISTRATION_TIMEOUT = 3 * 1000;
private static final int WAIT_TIMEOUT = 30 * 1000;
private final HttpClient httpclient = new DefaultHttpClient();
final HttpParams params = httpclient.getParams();
HttpResponse response;
Button Submit = (Button) findViewById(R.id.submitButton);
EditText textvalue = (EditText)findViewById(R.id.searcheditText);
//Onclick Listener
Submit.setOnClickListener(onClickListener)
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(final View v) {
switch(v.getId()){
case R.id.submitButton:
break;
}
};
protected void onPreExecute() {
//any code
}
#Override
protected String doInBackground(String... arg0) {
String URL = "url";
String username = "abc";
String password = "xyz";
try {
HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);
HttpPost httpPost = new HttpPost(URL);
//Any other parameters you would like to set
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("username",username));
nameValuePairs.add(new BasicNameValuePair("password",password));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Response from the Http Request
response = httpclient.execute(httpPost);
StatusLine statusLine = response.getStatusLine();
//Check the Http Request for success
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
}
else{
//Closes the connection.
Log.w("HTTP1:",statusLine.getReasonPhrase());
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}catch (Exception e) {
}
return null;
}
protected void onCancelled() {
}
protected void onPostExecute(String content) {
}
private void connecttopostdata() {
Server_Post task = new Server_Post();
task.execute(textvalue.getText().toString());
}
}
the response is in xml and i want to also dispaly the response on listviews.
Thanks in advance.
You need a context of an activity class to get button from findviewbyid . Make a constructor and find your views from there. Like..
// give context from where you are calling your AsyncTask
public Server_Post (Context context)
{
Button Submit = (Button) context.findViewById(R.id.submitButton);
EditText textvalue = (EditText)context.findViewById(R.id.searcheditText);
}