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.
Related
im new with Android Studio, and I want to connect Android Studio, to a database created in another compiler. When I execute the debugger and reach de line "BufferedReader bf = new BufferedReader(new InputStreamReader(conn.getInputStream()));", I get and Exception call "FileNotFoundException".
Can someone help me?
Thank you very much.
public class Menu_Login extends AppCompatActivity {
EditText usuario, password;
Button login;
String url_login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu_login);
usuario = (EditText) findViewById(R.id.escribir_nombre); // COMO DECLARAR UN EDIT TEXT
password = (EditText) findViewById(R.id.escribir_contraseƱa);
login = (Button) findViewById(R.id.click_boton);
final Context context = this;
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
String user = usuario.getText().toString();
String pass = password.getText().toString();
url_login = String.format("http://192.168.1.35/loguear?nombre=%s&password=%s",user,pass);
new MultiplyTask(context).execute(user);
}
});
}
public class MultiplyTask extends AsyncTask <String,Void,String>
{
Context context;
private MultiplyTask(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String value) {
TextView n = (TextView) findViewById (R.id.mostrar_resultado);
n.setText(value);
}
#Override
protected String doInBackground(String... params) {
try
{
URL url = new URL(url_login);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 );
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
BufferedReader bf = new BufferedReader(new InputStreamReader(conn.getInputStream()));
int status = conn.getResponseCode();
InputStream error = conn.getErrorStream();
String value = bf.readLine();
return value;
}
catch (Exception e)
{
System.out.println(e);
e.printStackTrace();
}
return null;
}
}
}
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.
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.
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();
}
}
This is my Activity class where i use AsyncTask to get data from a server:
public class UserProfileActivity extends Activity {
private ImageView userImage;
private TextView userName;
private TextView userLocation;
private TextView editInfo;
private TextView chnageImage;
private TextView userScore;
private ListView friendsList;
public ArrayAdapter<String> adapter;
public int score;
public int level;
public String image;
public String fname;
public String lname;
public String city;
public int id;
public String email;
protected Activity activity = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_profile);
userImage = (ImageView) findViewById(R.id.profileImage);
userName = (TextView) findViewById(R.id.userName_profile);
userLocation = (TextView) findViewById(R.id.userLocation_profile);
editInfo = (TextView) findViewById(R.id.edit_profile);
chnageImage = (TextView) findViewById(R.id.changeImage_profile);
userScore = (TextView) findViewById(R.id.userScore_profile);
friendsList = (ListView) findViewById(R.id.friendsList);
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
private InputStream is;
private StringBuilder sb;
private String result;
#Override
protected String doInBackground(String... params) {
try {
HttpPost httppost = new HttpPost(
"http://www.xxxxxxxxx.com/mobile/getProfileInfo");
HttpResponse response = SignUpActivity.httpclient
.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
}
try {
JSONObject jObj = new JSONObject(result);
String status = jObj.getString("status");
score = jObj.getInt("credits");
level = jObj.getInt("level");
image = jObj.getString("image");
fname = jObj.getString("fname");
lname = jObj.getString("lname");
city = jObj.getString("city");
id = jObj.getInt("user_id");
email = jObj.getString("email");
JSONArray friendsJsonArray = jObj.getJSONArray("friends");
int size = friendsJsonArray.length();
ArrayList<String> friendsNames = new ArrayList<String>();
String[] friendsIds = new String[size];
for (int i = 0; i < size; i++) {
friendsNames.add(friendsJsonArray.getJSONObject(i)
.getString("name"));
}
adapter = new ArrayAdapter<String>(getApplicationContext(),
R.layout.simple_listview_item, friendsNames);
} catch (Exception e) {
}
} catch (Exception e) {
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
friendsList.setAdapter(adapter);
userScore.setText(score + " points" + " level " + level);
userName.setText(fname + " " + lname);
userLocation.setText(city);
Bitmap bitmap = null;
try {
bitmap = BitmapFactory
.decodeStream((InputStream) new URL(image).getContent());
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
userImage.setImageBitmap(bitmap);
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
}
when this activity is loaded it shows all the default values and images and then changes when background code execution is competed(as excepted), but this takes 2-3 secs for which user will be seeing default values, which i dont want to. So how can i keep a spinner like this:
for 2-3 secs and then when the spinner disappears the activity must show the actual values.
Thank you
Refer the below code
private class FetchRSSFeeds extends AsyncTask<String, Void, Boolean> {
private ProgressDialog dialog = new ProgressDialog(HomeActivity.this);
/** progress dialog to show user that the backup is processing. */
/** application context. */
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
#Override
protected Boolean doInBackground(final String... args) {
try {
Utilities.arrayRSS = objRSSFeed
.FetchRSSFeeds(Constants.Feed_URL);
return true;
} catch (Exception e) {
Log.e("tag", "error", e);
return false;
}
}
#Override
protected void onPostExecute(final Boolean success) {
if (dialog.isShowing()) {
dialog.dismiss();
}
// Setting data to list adapter
setListData();
}
Do This:-
Declare the ProgressDialog at the Top.
ProgressDialog pd;
Start it in onPreExecute Method of Async Task.
pd=ProgressDialog.show(ActivityName.this,"","Please Wait",false);
Stop it in the onPostExecute Method.
pd.dismiss();
In onCreate method call some like below
mdialog=new Dialog(this);
new LongOperation().execute("");
Then override onPostExecute of AyncTask
#Override
protected void onPostExecute() {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
mdialog.dismiss();
}
});
}