Aplication unfortunately close but no code error - Java android [duplicate] - java

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 7 years ago.
Helo guys,
I'm new at android programming, I'm trying to make login application connect to localhost mysql with android studio based on this web. Here is code:
Mainactivity.java
public class Mainmenu extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainmenu);
Button login=(Button)findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent login=new Intent(v.getContext(),Login.class);
startActivity(login);
}
});
Button register=(Button)findViewById(R.id.register);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent regis= new Intent(v.getContext(),Register.class);
startActivity(regis);
}
});
Button exit=(Button)findViewById(R.id.exit);
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
Login.java
public class Login extends ActionBarActivity {
final EditText id=(EditText)findViewById(R.id.handphone);
final EditText pass=(EditText)findViewById(R.id.pass_login);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
TextView login=(TextView)findViewById(R.id.textView);
login.setText("Login to Human Tracker");
Button log=(Button)findViewById(R.id.login);
log.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String password=pass.getText().toString();
String handphone=id.getText().toString();
if (!password.equals("") && !handphone.equals("")) {
Toast.makeText(getApplication(),"Your id or password is wrong",Toast.LENGTH_SHORT).show();
} else {
masuk();
Toast.makeText(getApplication(),"Welcome", Toast.LENGTH_SHORT).show();
Intent user = new Intent(v.getContext(), User.class);
startActivity(user);
}
}
});
}
private void masuk(){
SharedPreferences prefs;
String prefName ="report";
InputStream is=null;
String result=null;
String line=null;
JSONObject jArray= null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("hp",id.getText().toString()));
try {
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost("http://10.0.0.2");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity=response.getEntity();
is=entity.getContent();
} catch (Exception e){
Log.e("Fail 1: Error in HTTP connection",e.toString());
Toast.makeText(getApplicationContext(),"Fail 1: Error in HTTP connection",Toast.LENGTH_SHORT).show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("Fail 2: Error converting result ", e.toString());
}
try
{
JSONObject jobject = new JSONObject(result);
String S_pwd = jobject.getString("pass");
String S_name = jobject.getString("name");
String S_id = jobject.getString("id");
if(S_pwd.equals(pass.getText().toString())) {
Toast.makeText(getBaseContext(), "Login Successfully",
Toast.LENGTH_SHORT).show();
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
//---save the values in the EditText view to preferences---
editor.putString("id", S_id);
editor.putString("name", S_name);
//---saves the values---
editor.commit();
Toast.makeText(getApplicationContext(),"Login success",Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getBaseContext(), "Login Failure \n" +
"\n Try Again", Toast.LENGTH_LONG).show();
id.setText("");
pass.setText("");
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
}
Everything is okay, i can go to User.java before add that private void masuk. Then im debug my application and no error. But why when i press login button on main menu(to go Login.java) it say 'Unfortunately Login has stopped'?

this will not work:
public class Login extends ActionBarActivity {
final EditText id=(EditText)findViewById(R.id.handphone);
final EditText pass=(EditText)findViewById(R.id.pass_login);
first of all call setContentView.
After that assign the Gui elements:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
EditText id=(EditText)findViewById(R.id.handphone);
EditText pass=(EditText)findViewById(R.id.pass_login);
or if you need them as class members:
EditText id;
EditText pass;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
id=(EditText)findViewById(R.id.handphone);
pass=(EditText)findViewById(R.id.pass_login);

Related

Getting 'java.lang.String.org.json.JSONObject.getString(java.lang.String)' exception

When I'm trying to pass an email value from EditText to php using get method by these Android code. I'm getting these error on my button click.
I have already checked my PHP code with constant variable it's fully working. So this error is from Android side.
EditText et;
Button b;
SharedPreferences sp;
JSONParser jsonParser=new JSONParser();
String url="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forgot_password);
et = (EditText)findViewById(R.id.editText);
b = (Button)findViewById(R.id.button1);
sp= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
url=sp.getString("url", "")+"forgotpassword.php";
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String email= et.getText().toString().trim();
if(email.equalsIgnoreCase("")){
et.setError("mail id");
}
else if(!Patterns.EMAIL_ADDRESS.matcher(email).matches()){
et.setError("mail format incorrect");
}
else {
Log.d("url=========", url);
try
{
List<NameValuePair> det=new ArrayList<NameValuePair>();
det.add(new BasicNameValuePair("email",email.trim()));
JSONParser jp=new JSONParser();
JSONObject js=new JSONObject();
js=jp.makeHttpRequest(url, "GET", det);
String result=js.getString("status");
if(result.equalsIgnoreCase("1"))
{
Toast.makeText(getApplicationContext(), "Password Sent ", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG).show();
}
}catch(Exception e)
{
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
});
}
}
I need to get text that I was given in EditText to my php. That's only I needed.

CheckBoxes are not getting cleared after clicking Next button

I am trying to implement a survey app in which we have to ask few questions and the question can have more than one answer. So I have used CheckBox for it but the problem I am facing is when I click on next button, the next question appears on the screen but the CheckBoxs which were checked for last question are still checked for the new question. So I want all the CheckBoxs cleared when I will click next button for next question.
public class SurveyActivity extends Activity {
Button submit,conti,nextbtn;
TextView head,survey,optn1,optn2,optn3,optn4;
String que,opt1,opt2,opt3,opt4;
CheckBox checkBox1,checkBox2,checkBox3,checkBox4;
int surveyno=127;
int questionno=1;
public final static String TAG_SUCCESS = "success";
public static final String EXTRA_MESSAGE = "Message";
String msg;
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_survey);
submit=(Button)findViewById(R.id.btnsumbit);
conti=(Button)findViewById(R.id.btncontinue);
head=(TextView)findViewById(R.id.tvproject);
nextbtn=(Button)findViewById(R.id.btnsubmtnxt);
survey=(TextView)findViewById(R.id.tvsurvey);
optn1=(TextView)findViewById(R.id.tvoptone);
optn2=(TextView)findViewById(R.id.tvopttwo);
optn3=(TextView)findViewById(R.id.tvoptthree);
optn4=(TextView)findViewById(R.id.tvoptfour);
checkBox1=(CheckBox)findViewById(R.id.chkopt1);
checkBox2=(CheckBox)findViewById(R.id.chkopt2);
checkBox3=(CheckBox)findViewById(R.id.chkopt3);
checkBox4=(CheckBox)findViewById(R.id.chkopt4);
nextbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
do
{
new FetchQuestion().execute();
questionno++;
}while(questionno>=22);
}
});
//font
Typeface type01=Typeface.createFromAsset(getAssets(),"HelveticaNeue-UltraLight.ttf");
head.setTypeface(type01);
submit.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent fours1 = new Intent(SurveyActivity.this, BeginAction.class);
startActivity(fours1);
}
});
conti.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent fours1 = new Intent(SurveyActivity.this, EntrpNxtStart.class);
startActivity(fours1);
}
});
new FetchQuestion().execute();
}
public void linkdn(View view)
{
Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.linkedin.com"));
startActivity(intent);
}
public void facebook(View view)
{
Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.facebook.com"));
startActivity(intent);
}
public void twiiter(View view)
{
Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://twitter.com/"));
startActivity(intent);
}
public void insta(View view)
{
Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.instagram.com/"));
startActivity(intent);
}
class FetchQuestion extends AsyncTask<String, String, String>
{
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(SurveyActivity.this);
progressDialog.setTitle("Contacting Servers");
progressDialog.setMessage("Logging in ...");
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(true);
progressDialog.show();
}
#Override
protected String doInBackground(String... args)
{
System.out.println("Doinbackground entered!");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("questionno",String.valueOf(questionno)));
params.add(new BasicNameValuePair("surveyno",String.valueOf(surveyno)));
JSONObject json = jsonParser.makeHttpRequest("http://www.tikox.com/ws/survey.php","POST", params);
System.out.println("json object made, php should exec now!" + json.toString());
Log.d("Create Response", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
System.out.println(" Details fetched Successfully!");
String msg = json.getString("message");
System.out.println(" msg " + msg);
que = json.getString("question");
System.out.println(" que " + que);
opt1 = json.getString("option1");
System.out.println(" opt1 " + opt1);
opt2 = json.getString("option2");
System.out.println(" opt2 " + opt2);
opt3 = json.getString("option3");
System.out.println(" opt3 " + opt3);
opt4 = json.getString("option4");
System.out.println(" opt4 " + opt4);
}
else
{
System.out.print("UnSuccessfull ");
msg = json.getString("message");
System.out.print(msg);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url)
{
progressDialog.dismiss();
survey.setText(que);
optn1.setText(opt1);
optn2.setText(opt2);
optn3.setText(opt3);
optn4.setText(opt4);
}
}
}
You need to clear the check boxes once next is clicked. Add below code to onPostExecute().
checkBox1.setChecked(false);
checkBox2.setChecked(false);
checkBox3.setChecked(false);
checkBox4.setChecked(false);
The CheckBox class inherit from CompoundButton which have a setChecked method that you can use right in your nextbtn click listener.
There is an example in the Android documentation for Checkboxes: https://developer.android.com/reference/android/widget/CheckBox.html
On Next click listener deselect all check boxes like
protected void onPostExecute(String file_url)
{
checkBox1.setSelected(false);
checkBox2.setSelected(false);
checkBox3.setSelected(false);
checkBox4.setSelected(false);
progressDialog.dismiss();
survey.setText(que);
optn1.setText(opt1);
optn2.setText(opt2);
optn3.setText(opt3);
optn4.setText(opt4);
}

app crashing when trying to connect Internet

I am working with android studio and whenever I try to connect to internet it show Dialog that "Unfortunately 'app name' stopped" and then if crashes.
I have updated the manifest file for permission as well. please provide any assistance, It might helpful.
Here is the code:
public class Login extends Activity {
TextView msg;
String user,pass;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
final EditText password;
TextView regLabel;
Button loginbt;
final EditText username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
regLabel = (TextView) findViewById(R.id.register_label);
msg = (TextView) findViewById(R.id.alert);
regLabel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent register_form = new Intent(Login.this,Register.class);
startActivity(register_form);
}
});
loginbt = (Button) findViewById(R.id.login);
loginbt.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
user = username.getText().toString();
pass = password.getText().toString();
if(user.length()>0 && pass.length()>0) {
try {
new LoginProcess().execute("http://url.com");
} catch (Exception le) {
msg.setText("Error:" + le);
}
}else{
msg.setText("Please Enter Username and Password!");
}
}
});
}
public class LoginProcess extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(Login.this);
protected void onPreExecute(){
Dialog.setMessage("Checking Authentication..");
Dialog.show();
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
Content = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
protected void onPostExecute(Void unused) {
if (Error != null) {
msg.setText("Error in Login: " + Error);
} else {
try {
JSONObject jsonObj = new JSONObject(Content);
String orgPass = jsonObj.getString("password");
if (orgPass.equals(pass)) {
Intent rp = new Intent(Login.this, Menu.class);
startActivity(rp);
finish();
} else {
msg.setText("Wrong Password");
}
} catch (Exception je) {
msg.setText("Error:" + je);
}
}
}
}
}

Android Studio:PutExtra & GetStringExtra With Online Database (no value)

I'm a beginner to Mobile Application Development, Currently i've been doing a login (online database) and Register.I wanna pass some argument to the next activity by using putExtra and getStringExtra. Below is my Code for Two Activities:
Login:
public class Login extends AppCompatActivity implements View.OnClickListener {
Button bLogin;
TextView registerLink;
EditText etUsername, etPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
bLogin = (Button) findViewById(R.id.bLogin);
etUsername = (EditText) findViewById(R.id.etUsername);
etPassword = (EditText) findViewById(R.id.etPassword);
registerLink = (TextView) findViewById(R.id.tvRegisterLink);
bLogin.setOnClickListener(this);
registerLink.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.bLogin:
String Username = etUsername.getText().toString();
String Password = etPassword.getText().toString();
Toast.makeText(this, "Loginin...", Toast.LENGTH_SHORT).show();
new Authenticate(this).execute(Username, Password);
break;
case R.id.tvRegisterLink:
Intent registerIntent = new Intent(Login.this, Register.class);
startActivity(registerIntent);
break;
}
}
public void ParentLogin()
{
String Username = etUsername.getText().toString();
String Password = etPassword.getText().toString();
Intent Main = new Intent(Login.this, MainActivity.class);
Main.putExtra("class","Parent");
Main.putExtra("username",Username);
Main.putExtra("password",Password);
startActivity(Main);
}
public void NannyLogin()
{
String Username = etUsername.getText().toString();
String Password = etPassword.getText().toString();
Intent Main = new Intent(Login.this, MainActivity.class);
Main.putExtra("class", "Nanny");
Main.putExtra("username",Username);
Main.putExtra("password",Password);
startActivity(Main);
}
public class Authenticate extends AsyncTask<String, Void, String> {
private Context context;
public Authenticate(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String Username = arg0[0];
String Password = arg0[1];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?username=" + URLEncoder.encode(Username, "UTF-8");
data += "&password=" + URLEncoder.encode(Password, "UTF-8");
link = "http://juliusgoh.comxa.com/Authenticate.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
return ("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
try {
JSONObject jsonObj = new JSONObject(result);
String query_result = jsonObj.getString("query_result");
switch (query_result) {
case "PSUCCESS":
Toast.makeText(context, "Login Successfully....Parent", Toast.LENGTH_SHORT).show();
ParentLogin();
break;
case "NSUCCESS":
Toast.makeText(context, "Login Successfully....Nanny", Toast.LENGTH_SHORT).show();
NannyLogin();
break;
case "FAILURE":
Toast.makeText(context, "Wrong Data. Login failed.", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(context, "Couldn't connect to remote database.", Toast.LENGTH_SHORT).show();
break;
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(context, "Error parsing JSON data.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(context, "Couldn't get any JSON data.", Toast.LENGTH_SHORT).show();
}
}
}
Second Activity:
public class MainActivity extends AppCompatActivity {
public String job;
public String username;
public String password;
TextView qwe;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
qwe = (TextView)findViewById(R.id.asd);
Intent intent = new Intent();
String strValue = intent.getStringExtra("class");
String strValue1 = intent.getStringExtra("username");
String strValue2 = intent.getStringExtra("password");
qwe.setText(strValue);
}
The code is working fine but in the second activity it shows nothing. im guessing it pass "" null argument.But i have no idea how to solve it.Kindly provide some advise. TQ <3
i've found the solution to my question, my second activity should type Intent intent = getIntent(); instead of Intent intent = new Intent;

Intent not passes my to my second Activity

The reason is that ones i fill in my user name, and password and click login button it is loads again at page requires tu fill user name, and password here is my source code
public class MainActivity extends Activity {
private EditText mTextUserName;
private EditText mTextPassword;
public String user_name;
public String pass_word;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextUserName = (EditText) findViewById(R.id.textUserName);
mTextPassword = (EditText) findViewById(R.id.textPassword);
final Button mButtonLogin = (Button) findViewById(R.id.buttonLogin);
mButtonLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
user_name = mTextUserName.getText().toString();
pass_word = mTextPassword.getText().toString();
// i am passing this intent
Intent goToNextActivity = new Intent(getApplicationContext(), ViewActivity.class);
goToNextActivity.putExtra("username", user_name);
goToNextActivity.putExtra("password", pass_word);
startActivity(goToNextActivity);
}
});
}
and in mine ViewActivity also
public class ViewActivity extends Activity {
private WebView webView;
public String pass_word;
public String user_name;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setDefaultFontSize(20);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
//here i get them
getIntent().getStringExtra("username");
getIntent().getStringExtra("password");
webView.loadUrl("http://intranet.mdis.uz/");
}
but this doest works(( i spended 8 hours on research but nothing helped me
I think this line is wrong:
Intent goToNextActivity = new Intent(getApplicationContext(), ViewActivity.class);
you should not use ApplicationContext when you trying to start new activity. Try this:
Intent goToNextActivity = new Intent(MainActivity.this, ViewActivity.class);
EDIT:
Try this, it should send data via POST:
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollbarFadingEnabled(false);
webView.getSettings().setDefaultFontSize(20);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
String username = getIntent().getStringExtra("username");
String password = getIntent().getStringExtra("password");
String data = "username=" + username + "&password=" + password;
webView.postUrl("http://intranet.mdis.uz/", EncodingUtils.getBytes(data, "base64"));
Let me try it.
Do the modification like this once and see plz...
public class MainActivity extends Activity {
private EditText mTextUserName;
private EditText mTextPassword;
public String user_name;
public String pass_word;
ConnectionClass cc;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextUserName = (EditText) findViewById(R.id.textUserName);
mTextPassword = (EditText) findViewById(R.id.textPassword);
cc=new ConnectionClass(this);
final Button mButtonLogin = (Button) findViewById(R.id.buttonLogin);
mButtonLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
user_name = mTextUserName.getText().toString();
pass_word = mTextPassword.getText().toString();
user_name=Uri.encode(user_name); // you can encode your parameters so that it does not throw exception for e.g it will replace a space as %20 otherwise if user enters special character error will come.. :)
pass_word=Uri.encode(pass_word); // same as above
String url="http://myserver.com/login.php?username="+user_name"&password="+user_name; // this is your server page url and passing username and password in plain url u can test it in browser to verify its working :)
new AsyncTask<String,Void,String>() // new android versions does not allow network operations on main thread but need to do asynchronously...
{
#Override
protected String doInBackground(String... params) {
return cc.getServerResponse(params[0]);
}
#Override
protected void onPostExecute(String result) { // this method runs on UI thread and is called when background process is done to make it more fancy u can use onPreExecute() to show a loader and dismiss the dialog here :)
super.onPostExecute(result);
if(result!=null)
{
if(result.equals("1") // assuming u r returning "1" if successful.
{
Toast.makeText(context, "Successful", 2000).show();
Intent goToNextActivity = new Intent(MainActivity.this, ViewActivity.class);
goToNextActivity.putExtra("username", user_name);
goToNextActivity.putExtra("password", pass_word);
startActivity(goToNextActivity);
}
}
else
Toast.makeText(context, "Network problem...", 2000).show();
}
}.execute(url);
}
}
});
}
Here is the ConnectionClass
public class ConnectionClass {
Context context;
public ConnectionClass(Context ctx) {
this.context=ctx;
}
public String getServerResponse(String urlLink)
{
try
{
HttpClient client = new DefaultHttpClient();
HttpPost http_get = new HttpPost(url);
HttpResponse responses;
responses = client.execute(http_get);
if (responses != null)
{
InputStream in = responses.getEntity().getContent();
String a = convertStreamToString(in);
// Log.i("RETURN",a+"");
return a;
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line);
}
}
catch (Exception e)
{
//Toast.makeText(context, e.toString()+" io2", Toast.LENGTH_LONG).show();
}
finally
{
try
{
is.close();
}
catch (Exception e)
{
//Toast.makeText(context, e.toString()+" io3", Toast.LENGTH_LONG).show();
}
}
return sb.toString();
}
}
Hope it helps u :)
Thx

Categories

Resources