need help, got confuse with AsyncTask - android

I'm new in android and i need to make AsyncTask, so my application can work on ICS. But after I read tutorials i still got confuse. Anyone, please help me to fix my code, i don't know what and where i must put in AsyncTask with my code like this. thank you
Login.java
package com.karismaelearning;
public class Login extends Activity {
public Koneksi linkurl;
String SERVER_URL;
private Button login, register, setting;
private EditText username, password;
public ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
setting = (Button)findViewById(R.id.bsetting);
login = (Button) findViewById(R.id.login);
register = (Button) findViewById(R.id.reg);
username = (EditText) findViewById(R.id.uname);
password = (EditText) findViewById(R.id.pass);
setting.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intentSet = new Intent(Login.this, UrlSetting.class);
startActivity(intentSet);
}
});
register.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intentReg = new Intent(Login.this, Register.class);
startActivity(intentReg);
}
});
login.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String response = null;
String mUsername = username.getText().toString();
String mPassword = password.getText().toString();
response = tryLogin(mUsername, mPassword).trim();
Log.d("Check","Here");
Log.d("Response",response);
if(response.toLowerCase().contains("berhasil"))
{
String nama = username.getText().toString();
Intent newIntent = new Intent(Login.this, MainPage.class);
Bundle bundle = new Bundle();
bundle.putString("nama", nama);
newIntent.putExtras(bundle);
startActivityForResult(newIntent, 0);
}
else
{
//Optional
//Kalau bisa dibuat constant untuk menghindari salah penulisan
String RoleError = "ROLE SALAH";
String UserError = "USER SALAH";
createDialog("Maaf", response.equals(RoleError) ? "Role Anda bukan Student!" : "Username Atau Password Salah!");
}
}
});
}
protected String tryLogin(String mUsername, String mPassword)
{
Log.d(" TryLoginCheck ","Here");
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String temp=null;
String parameters = "username="+mUsername+"&password="+mPassword;
System.out.println("UserName"+mUsername+"\n"+"password"+mPassword);
Log.d("Parameters",parameters);
try
{
;
linkurl = new Koneksi(this);
SERVER_URL = linkurl.getUrl();
SERVER_URL += "/mobile/Login.php";
url = new URL(SERVER_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
temp=sb.toString();
Log.d("Temp",temp);
response = sb.toString();
Log.d("Response",response);
Log.d("Sb Value",sb.toString());
isr.close();
reader.close();
}
catch(IOException e) {
Toast.makeText(this,e.toString(),Toast.LENGTH_SHORT).show();
}
return response;
}
class LoginTask extends AsyncTask<String, Void, Integer> {
public LoginTask(Login activity, ProgressDialog progressDialog){
}
#Override
protected void onPreExecute(){
progressDialog.show();
}
#Override
protected Integer doInBackground(String... arg0){
}
private void createDialog(String title, String text) {
AlertDialog ad = new AlertDialog.Builder(this)
.setPositiveButton("Ok", null)
.setTitle(title)
.setMessage(text)
.create();
ad.show();
}
}
login.java - edited -> is it like this?
package com.karismaelearning;
public class Login extends Activity {
public Koneksi linkurl;
String SERVER_URL;
private Button login, register, setting;
private EditText username, password;
public ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
setting = (Button)findViewById(R.id.bsetting);
login = (Button) findViewById(R.id.login);
register = (Button) findViewById(R.id.reg);
username = (EditText) findViewById(R.id.uname);
password = (EditText) findViewById(R.id.pass);
setting.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intentSet = new Intent(Login.this, UrlSetting.class);
startActivity(intentSet);
}
});
register.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intentReg = new Intent(Login.this, Register.class);
startActivity(intentReg);
}
});
login.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new LoginTask().execute();
}
});
}
protected String tryLogin(String mUsername, String mPassword){
Log.d(" TryLoginCheck ","Here");
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String temp=null;
String parameters = "username="+mUsername+"&password="+mPassword;
System.out.println("UserName"+mUsername+"\n"+"password"+mPassword);
Log.d("Parameters",parameters);
try{
linkurl = new Koneksi(this);
SERVER_URL = linkurl.getUrl();
SERVER_URL += "/mobile/Login.php";
url = new URL(SERVER_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
temp=sb.toString();
Log.d("Temp",temp);
response = sb.toString();
Log.d("Response",response);
Log.d("Sb Value",sb.toString());
isr.close();
reader.close();
}
catch(IOException e) {
Toast.makeText(this,e.toString(),Toast.LENGTH_SHORT).show();
}
return response;
}
public class LoginTask extends AsyncTask<String, Void, String> {
String response = null;
public LoginTask() {
}
#Override
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
String mUsername = username.getText().toString();
String mPassword = password.getText().toString();
response = tryLogin(mUsername, mPassword).trim();
return response;
}
protected void onPostExecute(String result){
super.onPostExecute(result);
Log.d("Check","Here");
Log.d("Response",response);
if(response.toLowerCase().contains("berhasil")){
String nama = username.getText().toString();
Intent newIntent = new Intent(Login.this, MainPage.class);
Bundle bundle = new Bundle();
bundle.putString("nama", nama);
newIntent.putExtras(bundle);
startActivityForResult(newIntent, 0);
}
else{
//Optional
//Kalau bisa dibuat constant untuk menghindari salah penulisan
String RoleError = "ROLE SALAH";
String UserError = "USER SALAH";
createDialog("Maaf", response.equals(RoleError) ? "Role Anda bukan Student!" : "Username Atau Password Salah!");
}
}
}
private void createDialog(String title, String text) {
AlertDialog ad = new AlertDialog.Builder(this)
.setPositiveButton("Ok", null)
.setTitle(title)
.setMessage(text)
.create();
ad.show();
}
}

use like that
class LoginTask extends AsyncTask<String, Void, Integer> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
progressDialog.show();
}
#Override
protected Integer doInBackground(String... arg0)
{
// do all login request here only
}
#Override
protected String onPostExecute(String arg0)
{
progressDialog.dismiss();
// get the response here and show where you want
}

Put in your OnClick method
new LoginTask().execute(stringParam);
to execute your method after clicking element.

In short:
You need to put your tryLogin() code into the doInBackground() method of the AsyncTask.
Incidentally, you should really take a look at your variable naming, the scope of your methods etc. Does tryLogin() really need to be protected? mUsername and mPassword are not member variables of the class, they are local variables.
http://source.android.com/source/code-style.html

Try below code:
public class Login extends Activity {
public Koneksi linkurl;
String SERVER_URL;
private Button login, register, setting;
private EditText username, password;
public ProgressDialog progressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
setting = (Button)findViewById(R.id.bsetting);
login = (Button) findViewById(R.id.login);
register = (Button) findViewById(R.id.reg);
username = (EditText) findViewById(R.id.uname);
password = (EditText) findViewById(R.id.pass);
setting.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intentSet = new Intent(Login.this, UrlSetting.class);
startActivity(intentSet);
}
});
register.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intentReg = new Intent(Login.this, Register.class);
startActivity(intentReg);
}
});
login.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
new LoginTask.execute();
}
});
}
protected String tryLogin(String mUsername, String mPassword)
{
Log.d(" TryLoginCheck ","Here");
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String temp=null;
String parameters = "username="+mUsername+"&password="+mPassword;
System.out.println("UserName"+mUsername+"\n"+"password"+mPassword);
Log.d("Parameters",parameters);
try
{
;
linkurl = new Koneksi(this);
SERVER_URL = linkurl.getUrl();
SERVER_URL += "/mobile/Login.php";
url = new URL(SERVER_URL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
temp=sb.toString();
Log.d("Temp",temp);
response = sb.toString();
Log.d("Response",response);
Log.d("Sb Value",sb.toString());
isr.close();
reader.close();
}
catch(IOException e)
{
Toast.makeText(this,e.toString(),Toast.LENGTH_SHORT).show();
}
return response;
}
class LoginTask extends AsyncTask<String, Void, String> {
private ProgressDialog progressDialog;
private Login activity;
private int id = -1;
public LoginTask(Login activity, ProgressDialog progressDialog)
{
this.activity = activity;
this.progressDialog = progressDialog;
}
#Override
protected void onPreExecute()
{
progressDialog.show();
}
#Override
protected Integer doInBackground(String... arg0)
{
String mUsername = username.getText().toString();
String mPassword = password.getText().toString();
response = tryLogin(mUsername, mPassword).trim();
return response;
}
protected Void onPostExecute(String result){
super.onPostExecute(result);
if(response.toLowerCase().contains("berhasil"))
{
String nama = username.getText().toString();
Intent newIntent = new Intent(Login.this, MainPage.class);
Bundle bundle = new Bundle();
bundle.putString("nama", nama);
newIntent.putExtras(bundle);
startActivityForResult(newIntent, 0);
}
else
{
String RoleError = "ROLE SALAH";
String UserError = "USER SALAH";
createDialog("Maaf", response.equals(RoleError) ? "Role Anda bukan Student!" : "Username Atau Password Salah!");
}
}
}
private void createDialog(String title, String text) {
AlertDialog ad = new AlertDialog.Builder(this)
.setPositiveButton("Ok", null)
.setTitle(title)
.setMessage(text)
.create();
ad.show();
}
}

Related

Move One activity to Another Activity using function

MainActivity.java
public class MainActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user_name = (EditText) findViewById(R.id.user_name);
password = (EditText)findViewById(R.id.password);
submit_btn = (Button) findViewById(R.id.submit);
submit_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Sender s = new Sender(v.getContext(),urlAddress,user_name,password);
s.execute();
cxt = getApplicationContext();
}
});
}
public void GoUserActivity(){
Intent i = new Intent(MainActivity.this,com.example.prakash.cinihive.UserActivity.class);
startActivity(i);
}
}
Sender.java
package com.example.prakash.cinihive;
public class Sender extends AsyncTask<Void,Void,String> {
Context c;
String urlAddress;
EditText user_name,password;
String UserName,Password;
ProgressDialog pd;
MainActivity main = new MainActivity();
public Sender(Context c, String urlAddress, EditText user_name, EditText password) {
this.c = c;
this.urlAddress = urlAddress;
this.user_name = user_name;
this.password = password;
UserName = user_name.getText().toString();
Password = password.getText().toString();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(c);
pd.setTitle("send");
pd.setMessage("Sending..Please wait");
pd.show();
}
#Override
protected String doInBackground(Void... voids) {
return this.send();
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
pd.dismiss();
if(response !=null){
//Toast.makeText(c,response,Toast.LENGTH_LONG).show();
//Log.d("Response",response);
if(response.equals("false")){
Toast.makeText(c,"Invalid Credentials",Toast.LENGTH_LONG).show();
}
else{
main.GoUserActivity();
//Toast.makeText(c,response,Toast.LENGTH_LONG).show();
}
user_name.setText("");
password.setText("");
}
else{
Toast.makeText(c,"Un succesfullll",Toast.LENGTH_LONG).show();
}
}
public String send(){
HttpURLConnection con = Connector.connect(urlAddress);
//Toast.makeText(c,con.toString(),Toast.LENGTH_LONG).show();
if(con==null){
Toast.makeText(c,"Connection Null",Toast.LENGTH_LONG).show();
return null;
}
try{
// Log.d("Connection status","Connection not null");
OutputStream os = con.getOutputStream();
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
bw.write(new DataPack(UserName,Password).Packdata());
bw.flush();
bw.close();
os.close();
int responseCode = con.getResponseCode();
Log.d("MYINT","Response Id :"+responseCode);
if(responseCode==con.HTTP_OK){
Log.d("Response code","Response code success");
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer response = new StringBuffer();
String line;
while((line=br.readLine())!=null){
response.append(line);
}
br.close();
return response.toString();
}else{
Log.d("Response code","Failure");
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
This is my code My problem was Intent Statement Not working in GoUserActivity funtion
At the same time Intent Statement Working well in OnCreate function.
When I try to run inside GoUserActivity,it will raise the runtime error(NullPoniterException "Intent i = new Intent(MainActivity.this,com.example.prakash.cinihive.UserActivity.class);")
I think you'll find things work better if you move your AsyncTask inside MainActivity as an inner class. You'll be able to call GoUserActivity() without having to new another instance of MainActivity, which you should never do.

APK file was built successfully with no errors but app isn't working

I developing an Android App that is connected to a database. Log in functioned successfully done. When I added Registration feature the app stopped working. APK file was built successfully and the main activity launches successfully also but when ever I click any button, the application stops. Here is the main activity code: `public class MainActivity extends AppCompatActivity {
SQLiteDatabase db;
String url;
EditText emailText, passText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().hide();
final TextView registerText = (TextView) findViewById(R.id.registertext);
final Button loginbtn = (Button) findViewById(R.id.login);
db = openOrCreateDatabase("User", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS Login(ID VARCHAR, NAME VARCHAR, pass VARCHAR);");
registerText.setOnClickListener(
new TextView.OnClickListener() {
public void onClick(View view){
Intent intent = new Intent(MainActivity.this, Register.class);
startActivity(intent);
}
}
);
loginbtn.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View view) {
//check connection
ConnectivityManager cm = (ConnectivityManager) getSystemService(getBaseContext().CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getNetworkInfo(0);
url = "http://skillsexchangecyprus.com/SEC/SkillsLogin.php";
//Check fields
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.activity_main);
final TextView alert = (TextView)findViewById(R.id.alert);
if (emailText.getText().toString().matches(" ") || passText.getText().toString().matches(" ")) {
Snackbar snackbar = Snackbar.make(relativeLayout, "Fill In Empty Fields", Snackbar.LENGTH_LONG);
snackbar.show();
} else {
new BackgroundTasks(alert).execute(url);
}
}});}
class BackgroundTasks extends AsyncTask <String, Void, String> {
TextView alert;
public BackgroundTasks(TextView textview) {
this.alert = textview;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
alert.setVisibility(View.VISIBLE);
alert.setText("Loading...");
}
String emtxt= emailText.getText().toString();
String passtxt= passText.getText().toString();
#Override
protected String doInBackground(String... strings) {
String result = "";
try {
URL url = new URL(strings[0]);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
final EditText emailText = (EditText) findViewById(R.id.email);
final EditText passText = (EditText) findViewById(R.id.password);
params.add(new BasicNameValuePair("email", emtxt));
params.add(new BasicNameValuePair("password", passtxt));
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
result = String.valueOf(builder.toString());
urlConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
#NonNull
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
StringBuilder out = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params) {
if (first)
first = false;
else
out.append("&");
out.append(URLEncoder.encode(pair.getName(), "UTF-8"));
out.append("=");
out.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return out.toString();
}
#Override
protected void onPostExecute(String temp) {
if (temp.trim().matches("Empty")) {
alert.setText("Invalid username or password");
} else {
alert.setVisibility(View.GONE);
String[] Split = temp.split("_");
db.execSQL("INSERT INTO Login values(' " + Split[1] + " ' , ' " + Split[0] + " ', ' " + Split[3] + " ')");
Intent intent = new Intent(MainActivity.this, FindSkill.class);
startActivity(intent);
}
}
}
}`
and here the registration code:
public class Register extends AppCompatActivity {
String url;
EditText name,email,pass;
Button registerBtn;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
registerBtn.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View view) {
ConnectivityManager cm = (ConnectivityManager) getSystemService(getBaseContext().CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getNetworkInfo(0);
url="http://skillsexchangecyprus.com/SEC/SkillsRegister.php";
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.regLayout);
name = (EditText) findViewById(R.id.namereg);
email = (EditText) findViewById(R.id.emailreg);
pass = (EditText) findViewById(R.id.passwordreg);
final TextView alert = (TextView)findViewById(R.id.alert);
if (name.getText().toString().matches("")||email.getText().toString().matches("")||pass.getText().toString().matches("")) {
Snackbar snackbar = Snackbar
.make(relativeLayout, "Fill in Empty Fields", Snackbar.LENGTH_LONG);
snackbar.show();
} else {
new BackgroundTasks(alert).execute(url);
}
}});}
class BackgroundTasks extends AsyncTask<String, Void, String> {
TextView alert;
public BackgroundTasks(TextView textview) {
this.alert = textview;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
alert.setVisibility(View.VISIBLE);
alert.setText("Saving....");
}
String nametxt = name.getText().toString();
String emtxt = email.getText().toString();
String passtxt = pass.getText().toString();
#Override
protected String doInBackground(String... strings) {
String task = "";
try {
URL url = new URL(strings[0]);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
ArrayList<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("nameReg", nametxt));
params.add(new BasicNameValuePair("emailReg", emtxt));
params.add(new BasicNameValuePair("passwordReg", passtxt));
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
StringBuilder builder = new StringBuilder();
String inputString;
while ((inputString = bufferedReader.readLine()) != null) {
builder.append(inputString);
}
task = String.valueOf(builder.toString());
urlConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
return task;
}
#NonNull
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
#Override
protected void onPostExecute(String temp) {
if (temp.trim().matches("Success")) {
alert.setText("Successfully saved");
} else {
String msg = "NOT FOUND";
alert.setVisibility(View.VISIBLE);
alert.setText("Try again");
}
}
}
}
Now Logcat is full of errors and warnings!!!
What you are doing is wrong.
String emtxt= emailText.getText().toString();
String passtxt= passText.getText().toString();
#Override
protected String doInBackground(String... strings) {
String result = "";
try {
URL url = new URL(strings[0]);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
final EditText emailText = (EditText) findViewById(R.id.email);
final EditText passText = (EditText) findViewById(R.id.password);
You are trying to create view object in background method and you are trying to get value from them before that. reformat code accordingly and check.

while navigating to the next page from login page, blank screen appears

I have integrated a webservice and after integrating it goes to the next page.
But the problem is while navigating to from login page to next page, it is showing blank screen and I do not understand what's the problem.
Kindly Help!!
Thanks in advance.
Here is my code
public class Mobile_Number_Activity extends Activity {
private EditText ed_Mobile_Number;
private Button btnSubmit;
private TextView Hyperlink;
private ProgressDialog pDialog;
private JSONObject json;
private int success = 0;
private String path = "xxx";
private String strMobileNumber = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mobile_number);
ed_Mobile_Number = (EditText) findViewById(R.id.ed_Mobile_Number);
btnSubmit = (Button) findViewById(R.id.btn_mobile_submit);
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (!ed_Mobile_Number.getText().toString().equals(""))
{
strMobileNumber = ed_Mobile_Number.getText().toString();
new SendPostRequest(getApplicationContext()).execute(strMobileNumber);
}
else
{
Toast.makeText(getApplicationContext(), "Please Enter Mobile Number", Toast.LENGTH_LONG).show();
}
}
});
}
Here is SendPost Request Class which extends Asyntask
public class SendPostRequest extends AsyncTask<String, Void, String> {
public static ProgressDialog pDialog;
private String path = "xxxx";
public String Mobile_Number = "";
private Context mContext;
public SendPostRequest(Context context)
{
this.mContext=context;
pDialog = new ProgressDialog(mContext);
pDialog.setTitle("Loading...");
pDialog.setMessage("Please wait...");
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.show();
}
#Override
protected String doInBackground(String... arg0)
{
try
{
Thread.sleep(40000);
String m_number=arg0[0];
URL url = new URL(path); // here is your URL path
JSONObject postDataParams = new JSONObject();
postDataParams.put("username", "data");
postDataParams.put("password", "data");
postDataParams.put("mobile", m_number);
System.out.println(m_number);
Mobile_Number=m_number;
Log.e("params", postDataParams.toString());
//conversion of 15 min to miliseconds :900000
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// conn.setReadTimeout(1500/* milliseconds */);
//conn.setConnectTimeout(1500 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
} else {
return new String("false : " + responseCode);
}
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
if (pDialog != null && pDialog.isShowing()) {
//Toast.makeText(mContext.getApplicationContext(), result,Toast.LENGTH_LONG).show();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(result);
String otp = jsonObject.optString("otp");
Log.d("otp value is", otp);
message(otp);
} catch (JSONException e) {
e.printStackTrace();
}
pDialog.dismiss();
}
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while (itr.hasNext()) {
String key = itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
public void message(String otp)
{
Intent myIntent = new Intent(this.mContext,OTP_Code_Activity.class);
myIntent.putExtra("Mobile Number", Mobile_Number);
System.out.println(Mobile_Number);
myIntent.putExtra("OTP Code", otp);
mContext.startActivity(myIntent);
pDialog.dismiss();
}
new SendPostRequest(getApplicationContext()).execute(strMobileNumber);
Change this to activity context.
new SendPostRequest(Mobile_Number_Activity.this).execute(strMobileNumber);
Delete(uninstall) the app from your phone, and run it again..It happens due to some issues with database. Or else I think you haven't mention the activity in the Manifest
Change
new SendPostRequest(getApplicationContext()).execute(strMobileNumber);
To
new SendPostRequest(this).execute(strMobileNumber);
And with Application Context, you can't show Dialog. You need to use Activity instance.
Change
SendPostRequest(Context context)
To
SendPostRequest(Activity context)
It might be helpful. Check log and see have any error in JSON Parse Exception as well.

Android web service error in http

In my project , to access the webservice am using http class which is not working properly and my project stops.
Can someone tell me an alternate way for accessing the webservice instead of using http.
Thank you in advance
class httpclass {
String result;
public String server_conn(String user_url)
{
// String user_url="";
String user_url3=user_url.replaceAll(" ","%20");
String user_url2=user_url3.replaceAll("\n","%0D");
HttpClient client = new DefaultHttpClient();
HttpGet siteRequest = new HttpGet(user_url2);
StringBuilder sb = new StringBuilder();
HttpResponse httpResponse;
try {
httpResponse = client.execute(siteRequest);
HttpEntity entity = httpResponse.getEntity();
InputStream in = entity.getContent();
String line = null;
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
result = sb.toString();
} catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
log in form
public class LoginForm extends FragmentActivity {
/** Called when the activity is first created. */
TextView txt1, txt2, err,forget;
EditText name;
EditText pass;
Button click,vend;
CheckBox savepass;
Button newuser;
Button signin;
#SuppressWarnings("unused")
private Cursor signin1;
SharedPreferences sharedPreferences=null;
public static String str1, str2;
public static String result;
public static String username;
ProgressDialog myProgressDialog = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); BugSenseHandler.initAndStartSession(this, "68640bea");
setContentView(R.layout.login);
vend=(Button)findViewById(R.id.vend);
name = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
savepass=(CheckBox)findViewById(R.id.savepass);
Button cancel = (Button) findViewById(R.id.cancel);
//Button back = (Button) findViewById(R.id.back);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent second = new Intent( LoginForm.this,canceluser.class);
startActivity(second);
finish();
}
});
sharedPreferences=PreferenceManager.getDefaultSharedPreferences(this);
String name1=sharedPreferences.getString("p_name", "");
name.setText(name1.toString());
String pass1=sharedPreferences.getString("p_pass", "");
pass.setText(pass1.toString());
//s forget=(TextView)findViewById(R.id.forget);
signin = (Button) findViewById(R.id.signin);
click = (Button) findViewById(R.id.click);
newuser = (Button) findViewById(R.id.signup);
vend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent viewIntent =
new Intent("android.intent.action.VIEW",
Uri.parse("http://www.iwedplanner.com/vendor/vendorhome.aspx"));
startActivity(viewIntent);
}});
click.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent1 = new Intent(LoginForm.this, forgetpwd.class);
startActivity(intent1);
finish();
}});
signin.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
if(name.getText().toString().equals(""))
{
alertbox("Message!","Enter Your Username");
name.requestFocus();
}
else if(pass.getText().toString().equals(""))
{
alertbox("Message!","Enter Your Password");
pass.requestFocus();
}
else
{
str1 = name.getText().toString();
str2 = pass.getText().toString();
boolean value = false;
// validuser();
ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isAvailable()) {
value = true;
openconn(str1, str2);
}
else
{
alertbox("Message!", "No Internet Connection!");
}
}
}
});
newuser.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
newuser();
}
});
}
public void openconn(String strr1, String strr2)
{
if (!strr1.equals("") && !strr2.equals(""))
{
err = (TextView) findViewById(R.id.err);
// String user_url = "http://iwedplanner.com/mobile/MLogin.aspx?uname="+ strr1 + "&pwd=" + strr2;
String user_url="http://mobileapps.iwedplanner.com/mobileapps/iwedplanner/mobile/MLogin.aspx?uname="+ strr1 + "&pwd=" + strr2;
httpclass obj = new httpclass();
result = obj.server_conn(user_url);
// alertbox("",""+result);
if (result != null)
{
StringTokenizer st = new StringTokenizer(result, "|");
result = st.nextToken();
if (result.equals("InvalidUser "))
{
Dialog locationError = new AlertDialog.Builder(
LoginForm.this).setIcon(0).setTitle("Message!")
.setPositiveButton(R.string.yes, null).setMessage(
"Sorry, Invalid Username or Password ")
.create();
locationError.show();
name.requestFocus();
}
else if(result.equals(strr1))
{
// Toast.makeText(getBaseContext(),"Valid User",Toast.LENGTH_SHORT).show();
if(savepass.isChecked())
{
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("p_name",name.getText().toString());
//editor.putString("p_pass",pass.getText().toString());
editor.commit();
}
else
{
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("p_name", "");
editor.putString("p_pass","");
editor.commit();
}
validuser();
}
else
{
alertbox("Message!","Error in network connection");
}
}
}
}
public void validuser()
{
username=str1;
name.setText("");
pass.setText("");
Intent userintent = new Intent(this, welcomeuser1.class);
//userintent.putExtra("name5",str1);
//Intent userintent=new Intent(this,WeddingInfo.class);
startActivity(userintent);
finish();
}
public void newuser() {
Intent userintent1 = new Intent(this, newuserform.class);
startActivity(userintent1);
finish();
}
protected void alertbox(String title, String mymessage) {
new AlertDialog.Builder(this)
.setMessage(mymessage)
.setTitle(title)
.setCancelable(true)
.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int whichButton) {
}
}).show();
}
#Override
public void onStart() {
super.onStart();
// The rest of your onStart() code.
// // EasyTracker.getInstance(this).activityStart(this); // Add this method.
}
#Override
public void onStop() {
super.onStop();
// The rest of your onStop() code.
// EasyTracker.getInstance(this).activityStop(this); // Add this method.
}
}
Error:duplicate files during packaging of APK C:\Users\sentientit\Documents\Wed Studio\app\build\outputs\apk\app-debug-unaligned.apk
Path in archive: META-INF/LICENSE.txt
Origin 1: C:\Users\sentientit\Documents\Wed Studio\app\libs\twitter4j.jar
1 Origin 2: C:\Users\sentientit.gradle\caches\modules-2\files-2.1\joda-
time\joda-time\2.4\89e9725439adffbbd41c5f5c215c136082b34a7f\joda-time-2.4.jar
You can ignore those files in your build.gradle:
android {
packagingOptions {
exclude 'META-INF/LICENSE.txt'
}
}
Error:Execution failed for task ':app:packageDebug'.
Duplicate files copied in APK META-INF/LICENSE.txt
File 1: C:\Users\sentientit\Documents\Wed Studio\app\libs\twitter4j.jar
File 2: C:\Users\sentientit\.gradle\cache``s\modules-2\files-2.1\joda-time\joda-time\2.4\89e9725439adffbbd41c5f5c215c136082b34a7f\joda-time-2.4.jar
You can do this way:
AsyncTask for Web service:
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(AsyncExample.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("Loading...");
pdLoading.show();
}
#Override
protected Void doInBackground(Void... params) {
String serverGETResponse = getJsonDataStringFormat("Your_Url", "GET", "", "LOGIN_ACTIVITY");
String serverPOSTResponse = getJsonDataStringFormat("Your_Url", "POST", "YOUR_JSON_STRING", "LOGIN_ACTIVITY");
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//this method will be running on UI thread
pdLoading.dismiss();
}
}
Now Get Response from server in Background thread:
public static String getJsonDataStringFormat(String url, String method,String jObjStr, String tag) {
InputStream is = null;
String Root_Response = null;
HttpResponse httpResponse;
HttpParams httpParameters = new BasicHttpParams();
DefaultHttpClient httpClient;
HttpConnectionParams.setConnectionTimeout(httpParameters,connectionTimeOut);
HttpConnectionParams.setSoTimeout(httpParameters, socketTimeOut);
try {
httpClient = new DefaultHttpClient(httpParameters);
url = url.replace(" ", "%20");
if (method == "POST") {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new StringEntity(jObjStr));
httpResponse = httpClient.execute(httpPost);
is = httpResponse.getEntity().getContent();
} else if (method == "GET") {
HttpGet httpGet = new HttpGet(new URI(url));
httpResponse = httpClient.execute(httpGet);
is = httpResponse.getEntity().getContent();
}
Root_Response = convertStreamToString(is);
Log.i(tag, Root_Response);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (URISyntaxException e) {
e.printStackTrace();
}
return Root_Response;
}
Convert Server's Response to String:
public static String convertStreamToString(InputStream inputStream)
throws IOException {
if (inputStream != null) {
StringBuilder sb = new StringBuilder();
String line;
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream, "UTF-8"));
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} finally {
inputStream.close();
}
return sb.toString();
} else {
return "";
}
}
Hope it will help you.
call the method server_conn() inside AsyncTask , and pass the url
private class AsyncTaskTest extends AsyncTask<String, Void, Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(String... strings) {
server_conn(strings[0]);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
}
}
and call the asynctastk using below syntax
new AsyncTaskTest().execute(url);
You are facing NetworkOnMainThread exception all you have to do is add this code :
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.build();
StrictMode.setThreadPolicy(policy);
For more details you can check developer site.

login page with httpget and asynctask in android

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);
}
}
}
}

Categories

Resources