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.
Related
Here i am facing a problem with password validation which is when i entering correct password but it is saying the password is incorrect. Here i am using rest web services below is my code please help me.
EditText password;
String Passwordstr;
Button btn_go;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
password = (EditText) findViewById(R.id.passET);
btn_go = (Button) findViewById(R.id.btn_go);
btn_go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Passwordstr = password.getText().toString();
if (Passwordstr.isEmpty()) {
Toast.makeText(Main2Activity.this, "Please, Enter Your Password.", Toast.LENGTH_SHORT).show();
} else {
new MyAsyncTask().execute(Passwordstr);
}
}
});
}
private class MyAsyncTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
String res = PostData(params);
return res;
}
public String PostData(String[] args) {
String s = "";
try {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://localhost:82/demo/login.php");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
s = readResponse(httpResponse);
} catch (Exception exception) {
}
return s;
}
protected void onPostExecute(String result) {
if (result.equals("true")) {
Intent intent = new Intent(Main2Activity.this, Main3Activity.class);
intent.putExtra("Password", Passwordstr);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Password incorrect", Toast.LENGTH_LONG).show();
}
}
public String readResponse(HttpResponse res) {
InputStream is = null;
String return_text = "";
try {
is = res.getEntity().getContent();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
String line = "";
StringBuffer sb = new StringBuffer();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
return_text = sb.toString();
} catch (Exception e) {
}
return return_text;
}
}
}
I am developing an android app in this my aim is to connect to a web page through web-server, here i am using Rest call and java code.Please help me any one.
In your post execute you have to check the null value not the true value like this
protected void onPostExecute(String result) {
if (result!=null) {
Intent intent = new Intent(Main2Activity.this, Main3Activity.class);
intent.putExtra("Password", Passwordstr);
//No Full Name
//MyHomeActivity.putExtra("GetDisplayName",user.getDisplayName());
// MyHomeActivity.putExtra("GetPhotoUrl",user.getPhotoUrl());
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Password incorrect", Toast.LENGTH_LONG).show();
// Hide the progress bar
// progressBar.setVisibility(View.GONE);
}
}
try this as you are not create post parameters pair with key and value.
List nameValuePair = new ArrayList(1);
nameValuePair.add(new BasicNameValuePair("password", "password"));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
HttpResponse response = httpClient.execute(httpPost);
Also hit rest api from postman or hurl.it with same password and check the response.
you can use android-async-http simple , fast
and u can access UI thread an Views on respond methods
RestClient.get("statuses/public_timeline.json", null, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
}
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Pull out the first event on the public timeline
JSONObject firstEvent = timeline.get(0);
String Text = firstEvent.getString("text");
textview.setText(Text);
// Do something with the response
System.out.println(tweetText);
}
});
I have an issue, which is not that big, but to the user it is bad.
The app basically gets the user's input of some place and, when the user clicks on the button, a URL to the Google API with the place on its parameter is sent to an AsyncTask, where it sends this URL via HttpGet and is returned a JSONArray with everything needed. The problem is, when I click on the button and the internet is not that good, the button seems to "freeze" like this:
My activity code is below:
public class MainActivity extends Activity{
...
protected void onCreate(Bundle savedInstanceState){...}
public void onResume()}
btnSearch.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String search = txtSearch.getText().toString();
try{
List<Location> locations = new SearchTask(MainActivity.this).execute(strSearch).get();
if(locations != null){
ArrayAdapter<Location> adapter = new ArrayAdapter<Location>(MainActivity.this, android.R.layout.simple_list_item_1, locations);
listView.setAdapter(adapter);
...
}
}
}
}
}
}
My AsyncTask class code is below:
public class SearchTask extends AsyncTask<String, Void, List<Location>>{
...
protected List<Location> doInBackground(String... params){
if(isNetworkAvailable()){
HttpGet httpGet = null;
HttpClient client = null;
HttpResponse response = null;
StringBuilder builder = null;
try{
String param = URLDecoder.decode(params[0], "UTF-8").replace(" ", "%20");
httpGet = new HttpGet("http://maps.googleapis.com/maps/api/geocode/json?address=" + param + "&sensor=false");
client = new DefaultHttpClient();
builder = new StringBuilder();
}
catch(UnsupportedEncodingException e){
Log.i("Error", e.getMessage());
}
try{
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
int val;
while((val = br.read()) != -1){
builder.append((char) val);
}
}
catch(IOException e){
Log.i("Error", e.getMessage());
}
JSONObject jsonObject = new JSONObject();
List<Location> listLocation = new ArrayList<Location>();
int countJson = 0;
try{
jsonObject = new JSONObject(builder.toString());
JSONArray jArray = jsonObject.getJSONArray("results");
countJson = jArray.length();
for(int i = 0; i < countJson; i++){
Location location = new Location();
String formattedAddress = ((JSONArray) jsonObject.get("results")).getJSONObject(i).getString("formatted_address");
double lat = ((JSONArray) jsonObject.get("results")).getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lat");
double lng = ((JSONArray) jsonObject.get("results")).getJSONObject(i).getJSONObject("geometry").getJSONObject("location").getDouble("lng");
location.setFormattedAddress(formattedAddress);
location.setLat(lat);
location.setLng(lng);
listLocation.add(location);
}
}
catch(JSONException e){
Log.i("Error", e.getMessage());
}
return listLocation;
}
else{
return null;
}
}
#Override
protected void onPreExecute(){
super.onPreExecute();
progress = new ProgressDialog(context);
progress.setMessage("Loading...");
progress.show();
}
#Override
protected void onPostExecute(List<Location> result){
super.onPostExecute();
progress.dismiss();
}
private boolean isNetworkAvailable(){
ConnectivityManager connManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connManager.getActiveNetworkInfo();
return info != null && info.isConnected();
}
}
The ListView is on the same xml of the EditView and the Button.
Is there a way to improve it in order to make the UI not behave like this?
Thanks!
Try this:
btnSearch.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
String search = txtSearch.getText().toString();
new SearchTask(MainActivity.this).execute(strSearch);
}
}
#Override
protected void onPostExecute(List<Location> locations){
if(locations != null){
ArrayAdapter<Location> adapter = new ArrayAdapter<Location>(MainActivity.this, android.R.layout.simple_list_item_1, locations);
listView.setAdapter(adapter);
}
progress.dismiss();
}
Hi I'm new to android and have task to create a login page that will connect with server and check user exist using http Get and AsyncTask and PHP API for this is ready. i went through few tutorials on AsyncTask and i understood but i m not sure how to work with http Get and AsyncTask. can anyone please help how to link both and create login page.
P.S: i have two EditText to accept username and password and two Buttons one for login and other for register and have corresponding DB as well.
This is sample code-
public class LoginActivity extends Activity
{
Intent i;
Button signin, signup;
String name = "", pass = "";
byte[] data;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream;
SharedPreferences app_preferences, pref;
List<NameValuePair> nameValuePairs;
EditText editTextId, editTextP;
SharedPreferences.Editor editor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
signin = (Button) findViewById(R.id.signin);
signup = (Button) findViewById(R.id.signup);
editTextId = (EditText) findViewById(R.id.editTextId);
editTextP = (EditText) findViewById(R.id.editTextP);
app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
String Str_user = app_preferences.getString("username", "0");
String Str_pass = app_preferences.getString("password", "0");
String Str_check = app_preferences.getString("checked", "no");
if (Str_check.equals("yes"))
{
editTextId.setText(Str_user);
editTextP.setText(Str_pass);
}
signin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
signin.setEnabled(false);
signup.setEnabled(false);
name = editTextId.getText().toString();
pass = editTextP.getText().toString();
String Str_check2 = app_preferences.getString("checked", "no");
if (Str_check2.equals("yes")) {
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("username", name);
editor.putString("password", pass);
editor.commit();
}
if (name.equals("") || pass.equals(""))
{
Toast.makeText(LoginActivity.this, "Blank Field..Please Enter", Toast.LENGTH_SHORT).show();
signin.setEnabled(true);
signup.setEnabled(true);
}
else
{
String emailPattern = "[a-zA-Z0-9._-]+#[a-z]+\\.+[a-z]+";
if(name.matches(emailPattern))
new LoginTask().execute();
signin.setEnabled(false);
signup.setEnabled(false);
}
}
});
signup.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
Move_next();
}
});
}
public void Move_to_next()
{
final Handler handle = new Handler();
Runnable delay = new Runnable() {
public void run() {
startActivity(new Intent(LoginActivity.this, SplashActivity.class));
finish();
}
};
handle.postDelayed(delay,2000);
}
public void Move_next()
{
startActivity(new Intent(LoginActivity.this, SignUpActivity.class));
finish();
}
#SuppressLint("NewApi")
private class LoginTask extends AsyncTask <Void, Void, String>
{
#SuppressLint("NewApi")
#Override
protected void onPreExecute()
{
super.onPreExecute();
// Show progress dialog here
}
#Override
protected String doInBackground(Void... arg0) {
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://website.com/yourpagename.php");
// Add your data
nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
response = httpclient.execute(httppost);
inputStream = response.getEntity().getContent();
data = new byte[256];
buffer = new StringBuffer();
int len = 0;
while (-1 != (len = inputStream.read(data))) {
buffer.append(new String(data, 0, len));
}
inputStream.close();
return buffer.toString();
}
catch (Exception e)
{
e.printStackTrace();
}
return "";
}
#SuppressLint("NewApi")
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Hide progress dialog here
if (buffer.charAt(0) == 'Y')
{
Toast.makeText(LoginActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
Move_to_next();
}
else
{
Toast.makeText(LoginActivity.this, "Invalid Username or password", Toast.LENGTH_SHORT).show();
signin.setEnabled(true);
signup.setEnabled(true);
}
}
}
}
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();
}
}
}
I have a login.php script which will validate the username and password entered in the android. The code is below
<?php
include('dbconnect.php');
$data=file_get_contents('php://input');
$json = json_decode($data);
$tablename = "users";
//username and password sent from android
$username=$json->{'username'};
$password=$json->{'password'};
//protecting mysql injection
$username = stripslashes($username);
$password = stripslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
$password = md5($password);
$sql = "SELECT id FROM $tablename WHERE u_username='$username' and password='$password'";
//Querying the database
$result=mysql_query($sql);
//If found, number of rows must be 1
if((mysql_num_rows($result))==1){
//creating session
session_register("$username");
session_register("$password");
print "success";
}else{
print "Incorrect details";
}
?>
I also have an android class from which the user will enter the username and password. The code is below.
public class LoginActivity extends Activity {
public static final String loginURI="http://.../login.php";
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
buttonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String userID = "";
userID=login(editTextUsername.getText().toString(), editTextPassword.getText().toString());
if (editTextPassword.getText().toString() != null & editTextUsername.getText().toString() != null){
//Used to move to the Cases Activity
Intent casesActivity = new Intent(getApplicationContext(), CasesActivity.class);
startActivity(casesActivity);
casesActivity.putExtra("username", userID);
}
else{
//Display Toaster for error
Toast.makeText(getApplicationContext(),"this is an error message", Toast.LENGTH_LONG).show();
}
}
});
private String login(String username, String password){
JSONObject jsonObject = new JSONObject();
String success = "";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(loginURI);
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,10000);
HttpConnectionParams.setSoTimeout(httpParams,10000);
try {
jsonObject.put("username", username);
Log.i("username", jsonObject.toString());
jsonObject.put("password", password);
Log.i("password", jsonObject.toString());
StringEntity stringEntity = new StringEntity(jsonObject.toString());
stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(stringEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
success = EntityUtils.toString(httpResponse.getEntity());
Log.i("success", success);
}
}catch (IOException e){
Log.e("Login_Issue", e.toString());
}catch (JSONException e) {
e.printStackTrace();
}
return success;
}
}
I get the following error: ERROR/AndroidRuntime(29611): FATAL EXCEPTION: main android.os.NetworkOnMainThreadException.
I understand that I need another thread and I was thinking of using AsyncTask, but I do not know where to put it in this class.
Could you also give me some advice in using JSON for sending and receiving data from android.
Thank you for your help,
you can change your code using AsyncTask by calling login method inside doInBackground and start next Activity on onPostExecute when login successful as :
private class LoginOperation extends AsyncTask<String, Void, String> {
String str_username=;
String str_password=;
public LoginOperation(String str_username,String str_password){
this.str_password= str_password;
this.str_username= str_username;
}
#Override
protected void onPreExecute() {
// show progress bar here
}
#Override
protected String doInBackground(String... params) {
// call login method here
String userID=login(str_username,str_password);
return userID;
}
#Override
protected void onPostExecute(String result) {
// start next Activity here
if(result !=null){
Intent casesActivity = new Intent(getApplicationContext(),
CasesActivity.class);
casesActivity.putExtra("username", result);
Your_Activiy.this.startActivity(casesActivity);
}
}
and start LoginOperation AsyncTask on button click as:
buttonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (editTextPassword.getText().toString() != null
& editTextUsername.getText().toString() != null){
// start AsyncTask here
new LoginOperation(editTextUsername.getText().toString(),
editTextPassword.getText().toString()).execute("");
}
else{
// your code here
}
}
});
}
The simple answer is to create a thread and only call the login within that thread, or an Async task(you can define it as a new class, and just call execute). Like this:
old code:
userID=login(editTextUsername.getText().toString(), editTextPassword.getText().toString());
new code:
Runnable runnable = new Runnable() {
void run() {
login(editTextUsername.getText().toString(), editTextPassword.getText().toString());
}
(new Thread(runnable)).start();