String Initialization for Dummies - android

OK I am messing something simple up here.
I have three Classes all within an Activity:
public class ActivityUserAccountCreate extends Activity implements
OnClickListener {
}
private class postToHttps extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
try {
createUserAccount();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public void createUserAccount() throws ClientProtocolException, IOException {
...
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
Log.d("Posting Username", usernameFinal);
nameValuePairs.add(new BasicNameValuePair("username", "usernameFinal"));
...
}
In my Activity class I initialize three Strings which are in the layout. Basically the user enters their username in a EditText. The strings are = to get the text form the field. That all works fine, but I am trying to use those same Strings in the createUserAccount(). I believe that the Strings are null at that point, so do I have to reinitialize these same three strings again in the createUserAccount()? If so, should I do it the same way that I did in in the Activity Class?
Thanks
OK I have edited according to the recommendation below, to:
...
new postToHttps().execute(usernameFinal,passwordFinal,userEmail);
...
private class postToHttps extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String usernameFinal = params[0];
String passwordFinal = params[1];
String userEmail = params[2];
try {
createUserAccount(usernameFinal, passwordFinal, userEmail);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public void createUserAccount(String usernameFinal, String passwordFinal, String userEmail) throws ClientProtocolException, IOException {
String uri = "editedout.php";
Log.d("Action", "Posting user data to php");
HttpClient client = new DefaultHttpClient();
HttpPost getMethod = new HttpPost(uri);
Log.d("Posting Location", uri);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
Log.d("Posting Username", usernameFinal);
nameValuePairs
.add(new BasicNameValuePair("username", usernameFinal));
Log.d("Posting Pass", passwordFinal);
nameValuePairs
.add(new BasicNameValuePair("password", passwordFinal));
nameValuePairs.add(new BasicNameValuePair("email", userEmail));
getMethod
.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
client.execute(getMethod);
Log.d("Action", "Finished Posting Data to PHP");
}
but am getting a crash. it looks like it is crashing in the doInBackground, but am still learning to read the LogCat.

You shouldn't have to be reinitializing anything, but if you are trying to pass in three Strings into your AsyncTask, I suggest taking advantage of the variable arguments used in doInBackground(String... params).
For example:
...
private class PostToHttps extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
String username = params[0];
String firstName = params[1];
String lastName = params[2];
createUserAccount(username, firstName, lastName);
}
...
PostToHttps httpsTask = new PostToHttps();
httpsTask.execute(usernameEditText.getText().toString(),
firstNameEditText.getText().toString(),
lastNameEditText.getText().toString);
...
public void createUserAccount(String username, String firstName, String lastName)
throws ClientProtocolException, IOException {
...

Related

how to check if logged in previosly in android app

i am working on android application, usually when we use different app then they requires only one time user login, and when we use next time then it does not require to login again, just like Facebook ,gmail etc
i also want to have such a functionality, so that it should save the username and password in shared preference, and i am using strong loop-back API(strong loop-back is basic requirement) following code i have just written it, but i want to use Access Token for it, can have give me the idea that how to use loop-back Access Token in android...???
public boolean checkLogin() {
final SharedPreferences prefs = this.getSharedPreferences(AndroidGPSTrackingActivity.class.getSimpleName(),
this.MODE_PRIVATE);
String userName = prefs.getString("userName", "");
if (userName.isEmpty()) {
Log.i("UserName", "UserName not found.");
return false;
}
String password = prefs.getString("password", "");
if (password.isEmpty()) {
Log.i("Password", "Password not found.");
return false;
}
mCheckTask = new CheckSavedLogin(userName, password, this);
mCheckTask.execute((Void) null);
return mCheckTask.execute((Void) null);//make this return true/false
}
and also:
public class CheckSavedLogin extends AsyncTask<Void, Void, Boolean> {
public final String mUserName;
public final String mPassword;
public boolean success;
public Context context;
CheckSavedLogin(String userName, String password, Context context) {
mUserName = userName;
mPassword = password;
this.context = context.getApplicationContext();
}
protected Boolean doInBackground(Void... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://173.242.94.66/scripts/appLogin.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("userName", mUserName));
nameValuePairs.add(new BasicNameValuePair("password", mPassword));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
String responseStr = EntityUtils.toString(response.getEntity());
JSONObject json = new JSONObject(responseStr);
success = json.getBoolean("success");
Log.d("Response", responseStr);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return success;
}
#Override
protected void onPostExecute(final Boolean success) {
mAuthTask = null;
showProgress(false);
if (success) {
storeLoginDetails(mUserName, mPassword);
//RETURN TRUE HERE?
}
}
#Override
protected void onCancelled() {
mAuthTask = null;
showProgress(false);
}
}

How to post data from an android application to a wamp server?

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

asynctask sqlite doesnt update

I am making a register screen for my project. After register data is sent to web database I want the app also update local sqlite database so that the next time user opens the app, he/she doesn't need to do the same operations if the register is successfull. My app is updating the web database with no problem but when I try to do sqlite update with a second asynctask it doesn't update sqlite, what am I missing? :(
Here is my code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
final EditText vmail=(EditText) findViewById(R.id.editText1);
final EditText vpassword=(EditText) findViewById(R.id.editText2);
final EditText vnickname=(EditText) findViewById(R.id.editText3);
Button button2=(Button) findViewById(R.id.button1);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mail=vmail.getText().toString();
password=vpassword.getText().toString();
mynickname=vnickname.getText().toString();
new AsyncTaskClass().execute();
}
});
}
class AsyncTaskClass extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(Void... params) {
String reverseString =null;
try
{
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("mail",mail));
nameValuePairs.add(new BasicNameValuePair("password",password));
nameValuePairs.add(new BasicNameValuePair("mynickname",mynickname));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("wwwmysite.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response = httpclient.execute(httppost, responseHandler);
reverseString = response;
} catch (ClientProtocolException e) {
Log.e("log_tag", "Error converting result " + e.toString());
} catch (IOException e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return reverseString;
}
protected void onPostExecute(String reverseString) {
if (reverseString.contains("success")){
new AsyncTaskClass2().execute();
}else{
Toast.makeText(getApplicationContext(), reverseString, Toast.LENGTH_LONG).show();
}
}
}
class AsyncTaskClass2 extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(Void... params) {
String reverseString =null;
try
{
KayitEkle(Array.get(nameValuePairs, 0).toString(),Array.get(nameValuePairs, 1).toString(),Array.get(nameValuePairs, 2).toString());
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return reverseString;
}
protected void onPostExecute(String reverseString) {
startActivity(new Intent(registergame.this, (mygamescreen.class)));
}
}
private void KayitEkle(String nick, String mail, String password){
SQLiteDatabase db = users.getWritableDatabase();
ContentValues veriler = new ContentValues();
veriler.put("nick", nick);
veriler.put("mail",mail);
veriler.put("password",password);
db.insertOrThrow("ogrenciisim", null, veriler);
}
}
Put a debugger to see if it is actually calling AsyncTaskClass2 doInBackground() method. If it does, then check the value returned by method insertOrThrow(). If return value is -1 then you need to check for that. This link will give you some insight
You declared your nameValuePairs-variable only in your doInBackground-Method of your 1st AsyncTask:
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
You could simply solve it, if you use your class-attribute nameValuePairs:
nameValuePairs = new ArrayList<NameValuePair>();
But as a general aspect, I do not see any cause why you should use a 2nd AsyncTask. Why don't you call the method
KayitEkle(Array.get(nameValuePairs, 0).toString(),Array.get(nameValuePairs, 1).toString(),Array.get(nameValuePairs, 2).toString());
in the doInBackground-Method of your 1st AsyncTask?

Android Login with HTTP post, get results

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.

android http post asynctask

Please can anyone tell me how to make an http post to work in the background with AsyncTask and how to pass the parameters to the AsyncTask? All the examples that I found were not clear enough for me and they were about downloading a file.
I'm running this code in my main activity and my problem is when the code sends the info to the server the app slows down as if it is frozen for 2 to 3 sec's then it continues to work fine until the next send. This http post sends four variables to the server (book, libadd, and time) the fourth is fixed (name)
Thanks in advance
public void SticketFunction(double book, double libadd, long time){
Log.v("log_tag", "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% SticketFunction()");
//HttpClient
HttpClient nnSticket = new DefaultHttpClient();
//Response handler
ResponseHandler<String> res = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("http://www.books-something.com");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("book", book+""));
nameValuePairs.add(new BasicNameValuePair("libAss", libass+""));
nameValuePairs.add(new BasicNameValuePair("Time", time+""));
nameValuePairs.add(new BasicNameValuePair("name", "jack"));
//Encode and set entity
postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
//Execute
//manSticket.execute(postMethod);
String response =Sticket.execute(postMethod, res).replaceAll("<(.|\n)*?>","");
if (response.equals("Done")){
//Log.v("log_tag", "!!!!!!!!!!!!!!!!!! SticketFunction got a DONE!");
}
else Log.v("log_tag", "!!!!!!!?????????? SticketFunction Bad or no response: " + response);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
//Log.v("log_tag", "???????????????????? SticketFunction Client Exception");
} catch (IOException e) {
// TODO Auto-generated catch block
//Log.v("log_tag", "???????????????????? IO Exception");
}
}
}
At first,
You put a class like following:
public class AsyncHttpPost extends AsyncTask<String, String, String> {
interface Listener {
void onResult(String result);
}
private Listener mListener;
private HashMap<String, String> mData = null;// post data
/**
* constructor
*/
public AsyncHttpPost(HashMap<String, String> data) {
mData = data;
}
public void setListener(Listener listener) {
mListener = listener;
}
/**
* background
*/
#Override
protected String doInBackground(String... params) {
byte[] result = null;
String str = "";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);// in this case, params[0] is URL
try {
// set up post data
ArrayList<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
Iterator<String> it = mData.keySet().iterator();
while (it.hasNext()) {
String key = it.next();
nameValuePair.add(new BasicNameValuePair(key, mData.get(key)));
}
post.setEntity(new UrlEncodedFormEntity(nameValuePair, "UTF-8"));
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpURLConnection.HTTP_OK){
result = EntityUtils.toByteArray(response.getEntity());
str = new String(result, "UTF-8");
}
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
catch (Exception e) {
}
return str;
}
/**
* on getting result
*/
#Override
protected void onPostExecute(String result) {
// something...
if (mListener != null) {
mListener.onResult(result)
}
}
}
Now.
You just write some lines like following:
HashMap<String, String> data = new HashMap<String, String>();
data.put("key1", "value1");
data.put("key2", "value2");
AsyncHttpPost asyncHttpPost = new AsyncHttpPost(data);
asyncHttpPost.setListener(new AsyncHttpPost.Listener(){
#Override
public void onResult(String result) {
// do something, using return value from network
}
});
asyncHttpPost.execute("http://example.com");
First i would not recommend do a Http request in a AsyncTask, you better try a Service instead. Going back to the issue on how to pass parameter into an AsyncTask when you declared it you can defined each Object class of the AsyncTask like this.
public AsyncTask <Params,Progress,Result> {
}
so in your task you should go like this
public MyTask extends<String,Void,Void>{
public Void doInBackground(String... params){//those Params are String because it's declared like that
}
}
To use it, it's quite simple
new MyTask().execute("param1","param2","param3")

Categories

Resources