Activity closes on button press - android

I'm having a bit of trouble with a simple app I'm making.
I'll include the code:
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import java.net.URL;
public class login extends AppCompatActivity {
EditText user;
EditText pass;
boolean result_back;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button log = (Button) findViewById(R.id.btLogIn2);
log.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
login(v);
}
});
}
public void login(View v)
{
HttpClient client = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpResponse response = null;
user = (EditText) findViewById(R.id.eTUser);
String usuario = user.toString();
pass = (EditText) findViewById(R.id.eTPass);
String passw = pass.toString();
String parametros = "?usuario=" + usuario + "&password=" + passw;
HttpGet httpGet = new HttpGet("http://gie.byethost.com/acces.php" + parametros);
Toast toast2 = Toast.makeText(getApplicationContext(), "Enviando datos", Toast.LENGTH_SHORT);
toast2.show();
try
{
response = client.execute(httpGet, localContext);
toast2 = Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_SHORT);
toast2.show();
}
catch (Exception e)
{
}
// response.toString();
if (response.toString().equalsIgnoreCase("1"))
{
Toast toast1 = Toast.makeText(getApplicationContext(), "Login correcto", Toast.LENGTH_SHORT);
toast1.show();
} else
if (response.toString().equalsIgnoreCase("0"))
{
Toast toast1 = Toast.makeText(getApplicationContext(), "Error de login", Toast.LENGTH_SHORT);
toast1.show();
}
}
}
There's only one button here and neither toast is showing, so I don't see where the app is crashing. Also, I'm a bit new in Android programming, so this may have an obvious solution.
Any comments will be appreciated!

You're doing a network transaction on the main thread. Never do that (or any blocking behavior) on the main thread. Your app might be crashing with an error in logcat related to "StrictMode".
Instead, you need to put all your blocking work on another thread. Android has very specific patterns about how to do that. It's not like you would expect in a normal java app.
You might want to consider doing a search for "android asynchronous programming" and learn about things like AsyncTask, Loader, and Service. There are a lot of great tutorials out there on how to use them. Please don't use Thread directly, as that will only cause you pain.

Related

Fatal exception in main thread [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 9 years ago.
I am new to android. My project is related to networking. I am getting this error
FATAL EXCEPTION: main
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java1133)
...
...
My code is :
package com.example.simpleclientactivity;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SimpleClientActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField1;
private Button button;
private String messsage;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textField1 = (EditText) findViewById(R.id.editText1); //reference to the text field
button = (Button) findViewById(R.id.button1); //reference to the send button
//Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
messsage = textField1.getText().toString(); //get the text message on the text field
textField1.setText(""); //Reset the text field to blank
try {
client = new Socket("10.0.2.2", 4444); //connect to server
printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(messsage); //write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); //closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
Here is main.xml code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"`enter code here`
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="83dp"
android:ems="10"
android:text="Client" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="53dp"
android:text="Send" />
</RelativeLayout>
It's not even displaying the toast message after clicking the button. However it's showing error in android.os.NetworkOnMainThreadException.
Try this..
This exception is thrown when an application attempts to perform a networking operation on its main thread
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
messsage = textField1.getText().toString(); //get the text message on the text field
textField1.setText(""); //Reset the text field to blank
new MyClass().execute(messsage);
}
});
MyClass.class AsyncTask
class MyClass extends AsyncTask<String, Void, String> {
private Exception exception;
protected String doInBackground(String... messsage) {
try {
client = new Socket("10.0.2.2", 4444); //connect to server
printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(messsage); //write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); //closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void onPostExecute(String result) {
// TODO: check this.exception
// TODO: do something with the feed
}
}
You cannot perform network IO on the UI thread on Honeycomb. Technically it is possible on earlier versions of Android, but is a really bad idea as it will cause your app to stop responding, and can result in the OS killing your app for being badly behaved. You'll need to run a background process or use AsyncTask to perform your network transaction on a background thread.
There is an article about Painless Threading on the Android developer site which is a good introduction to this, and will provide you with much better depth of answer than can be realistically provided here.
You have to put your code that access the internet on a thread
new Thread(new Runnable(){
#Override
public void run(){
//your code that access internet here
}
}).start();
try this code
package com.example.simpleclientactivity;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SimpleClientActivity extends Activity {
private Socket client;
private PrintWriter printwriter;
private EditText textField1;
private Button button;
private String messsage;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textField1 = (EditText) findViewById(R.id.editText1); //reference to the text field
button = (Button) findViewById(R.id.button1); //reference to the send button
//Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
messsage = textField1.getText().toString(); //get the text message on the text field
textField1.setText(""); //Reset the text field to blank
new GetCategory().execute(message);
}
});
}
//add inner class
class GetCategory extends AsyncTask<Void, Void, ArrayList<AbstractDetail>>{
protected ArrayList<AbstractDetail> doInBackground(String... messsage) {
try {
client = new Socket("10.0.2.2", 4444); //connect to server
printwriter = new PrintWriter(client.getOutputStream(),true);
printwriter.write(messsage); //write the message to output stream
printwriter.flush();
printwriter.close();
client.close(); //closing the connection
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(ArrayList<AbstractDetail> result)
{
}
}
}
}
Problem
You can not access network over UI thread. You are accessing Network through UI thread that's why you are getting NetworkOnMainThreadException.
Solution
Create new thread and access Network over that Thread.
OR
Use AsyncTask to do network related work on doInBackgroung() and for updating UI onPostExecute().

Finish an activity,get string typed result from a class and use that result to another activity

I'm new in android environment and started a Software development project, so my knowledge is too few in it. I need help in detail.
Problem details:
Project is on ANDROID OCR code source from github Robert m.theis
currently it's outcome is - while i take an image of any written text,it retrieves quite exact output using tesseract engine as text and search in internet.
my work is -
use the text string (digits ) and call to a phone operator.
my project name is automated mobile card recharging system.
so that i took result text from a method getText() class named OcrResult.java and put into my own activity. But i don't know why this don't working in real device.
it builds, run in emulator, but in real device at least it should show messages! But it doesn't.
i also added in manifest.xml file as (angel braces are remover here)
under activity
activity android:name="edu.sfsu.cs.orange.ocr.call.CallManager"
under application
uses-permission android:name="android.permission.CALL_PHONE"
here my code is
package edu.sfsu.cs.orange.ocr.call;
import edu.sfsu.cs.orange.ocr.OcrResult;
import edu.sfsu.cs.orange.ocr.CaptureActivity;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;
public class CallManager extends Activity
{
public static final String preString = "*111*";
public static final String postString = "#";
//to store retrieved digits
String finalString;
//to get text result from ocr result
OcrResult getStringResult = new OcrResult();
String middleString = getStringResult.getText();
//if it fails to scan desired digit,call the process again
CaptureActivity tryProcessAgain = new CaptureActivity();
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public void setString(String x)
{
middleString = x;
}
public String getString( String toBeInserted)
{
if(toBeInserted.length() == 16)
{
int counter = 0;
char [] insertHere = new char[16];
for(int verifier = 0; verifier < 16; verifier ++)
{
insertHere[verifier] = toBeInserted.charAt(verifier);
if(!Character.isDigit(insertHere[verifier]))
{
break;
}
counter ++;
}
if(counter == 16)
{
finalString = preString + toBeInserted + postString;
return finalString;
}
else
{
// #SuppressWarnings("unused")
//Toast toast = Toast.makeText(this, " number scan invalid.....OCR failed. Please try again.", Toast.LENGTH_SHORT);
//toast.show();
return middleString;
}
}
else
{
//#SuppressWarnings("unused")
//Toast toast = Toast.makeText(this, " number scannin invalid...OCR failed. Please try again.", Toast.LENGTH_SHORT);
//toast.show();
return middleString;
}
}
public void CallToOperator(String callMe)
{
Toast toast = Toast.makeText(this,finalString,Toast.LENGTH_SHORT);
toast.show();
//Toast toast1 = Toast.makeText(this,middleString,Toast.LENGTH_SHORT);
//toast1.show();
if(callMe == finalString)
{
try
{
startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + finalString)));
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
tryProcessAgain.onShutterButtonPressContinuous();
}
}
}

Connecting android client to C server

I am having trouble connecting my android client to a C server that I wrote. I found another thread with a similar question but unfortunately it was closed saying that it was too narrow. I hope that somebody can answer it here since this is relevant to me as well and all sample codes that I could find online only had the android client connecting to an android server. My client code is the following:
package edu.upenn.seas.cis542;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.os.Debug;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Try_uiActivity extends Activity
{
//private EditText serverIp;
private Button connectPhones;
private String serverIpAddress = "MY IP ADDRESS";
private boolean connected = false;
private Handler handler = new Handler();
final int SERVERPORT = 8080;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//NumberPicker t1 = (NumberPicker)findViewById(R.id.numberPicker3);
//t1.setRange(1, 5);
setContentView(R.layout.main);
}
/*
* When the Submit button is clicked, this method
* gets called.
*/
public void onSubmitClick(View view) {
int item1, item2, item3;
NumberPicker t1 = (NumberPicker)findViewById(R.id.numberPicker1);
item1 = t1.getCurrent();
NumberPicker t2 = (NumberPicker)findViewById(R.id.numberPicker2);
item2 = t2.getCurrent();
NumberPicker t3 = (NumberPicker)findViewById(R.id.numberPicker3);
item3 = t3.getCurrent();
String userInput = "" + item1 + item2 + item3;
//Log.out("Before connecting");
if (!connected) {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Toast toast=Toast.makeText(this, serverAddr.toString(), Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
Socket socket = new Socket(serverAddr, SERVERPORT);
connected = true;
} catch (Exception e) {
Toast toast=Toast.makeText(this, "Error2", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
e.printStackTrace();
connected = false;
}
}
}
}
I omitted what I want to do after it is connecting because just creating the socket already gives me an error. My C server opens a connection on the same port that the android program is connecting to. When I tested the server with a java client file, it worked fine. Does anybody know a solution to this? I also added the permissions to the Android Manifest, but that didn't solve the issue. Thanks!

My Intent script always showing an error

i'm creating a login application
the login script is ok it's returned true and false
if the response returns true or 1, i want to make it to go to another activity called inputBarcode, the eclipse showing an error on my Intent line and i don't know what to do
i didn't know the other variations of making Intents
this is my full code, the Intent that i want to call is on the bottom after if(res.equals("1")){ :
package com.nigmagrid.go;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
//import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
public class login extends Activity {
String lokasiTugas;
boolean status_npp;
boolean status_password;
boolean status_lokasi;
Button button;
EditText usernameEditText, passwordEditText;
TextView error;
Spinner lokasiSpinner;
final int minNPP = 3;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.login);
final Button button = (Button) findViewById(R.id.login_button);
final EditText usernameEditText = (EditText) findViewById(R.id.login_npp);
final EditText passwordEditText = (EditText) findViewById(R.id.login_password);
final Spinner lokasiSpinner = (Spinner) findViewById(R.id.spinner1);
final TextView error = (TextView) findViewById(R.id.login_status);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.lokasi_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
lokasiSpinner.setAdapter(adapter);
lokasiSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView adapter, View v, int i, long lng) {
//Toast.makeText(getApplicationContext(), adapter.getItemAtPosition(i).toString(), Toast.LENGTH_SHORT).show();
lokasiTugas = adapter.getItemAtPosition(i).toString();
}
#Override
public void onNothingSelected(AdapterView arg0) {
//do something else
}
});
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
error.setText("Menghubungkan ke server...");
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username", usernameEditText.getText().toString()));
postParameters.add(new BasicNameValuePair("password", passwordEditText.getText().toString()));
String response = null;
String sNPP = usernameEditText.getText().toString().replace(" ", "");
String sPassword = passwordEditText.getText().toString();
// validasi NPP
if(sNPP.length()<=minNPP){
usernameEditText.setError("NPP minimal "+minNPP+" angka");
status_npp = false;
}else{
status_npp = true;
//Toast.makeText(getApplicationContext(), "NPP Anda : "+sNPP, Toast.LENGTH_SHORT).show();
}
// validasi Password
if(sPassword.length()<1){
passwordEditText.setError("Kata sandi diperlukan");
status_password = false;
}else{
status_password = true;
}
//validasi lokasiTugas
if(lokasiTugas.equals("Pilih Lokasi")){
Toast.makeText(getApplicationContext(), "Lokasi Tugas diperlukan", Toast.LENGTH_SHORT).show();
status_lokasi = false;
}else{
status_lokasi = true;
}
// pengecekan akhir
if(status_npp == true && status_password == true && status_lokasi == true){
//Toast.makeText(getApplicationContext(), "NPP Anda : "+sNPP+"\nLokasi : "+lokasiTugas, Toast.LENGTH_SHORT).show();
//fungsi login disini :D
try{
// variabel cek-nya ganti
String cek = "http://almezuflash.zxq.net/kspt-android/ceklogin.php";
response = CustomHttpClient.excecuteHttpPost(cek, postParameters);
String res = response.toString();
res = res.replaceAll("\\s", "");
Toast.makeText(getApplicationContext(), res, Toast.LENGTH_SHORT).show();
if(res.equals("1")){
error.setText("Login sukses");
Toast.makeText(getApplicationContext(), "Login Sukses", Toast.LENGTH_SHORT).show();
// i want to make Intent but eclipse says error, and i don't know what to do
Intent doBarcode = new Intent(parent, inputBarcode.class);
startActivity(doBarcode);
}else{
error.setText("Login gagal");
//Toast.makeText(getApplicationContext(), "Login Gagal", Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
//error.setText(e.toString());
error.setText("Terjadi kesalahan, silahkan periksa koneksi internet anda");
}
}else{
//Toast.makeText(getApplicationContext(), "Otorisasi Gagal", Toast.LENGTH_SHORT).show();
status_npp = false;
status_password = false;
status_lokasi = false;
error.setText("Login gagal, silahkan periksa kembali");
}
}
});
}
}
Sorry for my bad english, i'm from Indonesia fyi :D
Did you make sure to add the inputBarCode activity to your AndroidManifiest? If you did not, then that will give a runtime error. If thats no the problem, then possibly changing
Intent doBarcode = new Intent(parent, inputBarcode.class);
to
Intent doBarcode = new Intent(this, inputBarcode.class);
will solve your problem. I'm not familiar with the parent variable being used.
I hope that helps.
Try instead of
Intent doBarcode = new Intent(parent, inputBarcode.class);
use this code:
Intent doBarcode = new Intent(login.this, inputBarcode.class);

login Issue in android

I have a login page, it works fine when i put correct username and password but for login failure its not working how to handle this.
In android i don't have any idea if any one can provide code please
here is my code :
package com.android;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.AndroidHttpTransport;
import org.xmlpull.v1.XmlPullParserException;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.*;
public class Login extends Activity {
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL ="http:.asmx?op=LoginRequest";
private static final String SOAP_ACTION = "http://tempuri.org/Login";
//private String login="";
private static final String METHOD_NAME = "Login";
ImageButton login_button,sign_button;
TextView m,p,f,email,password,forgot_password;
EditText emailid,epassword;
AlertDialog authProgressDialog;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login);
email=(TextView)findViewById(R.id.email);
password=(TextView)findViewById(R.id.password);
forgot_password=(TextView)findViewById(R.id.forgot);
Context context = email.getContext();
Typeface font=Typeface.createFromAsset(context.getAssets(),"arial.ttf");
email.setTypeface(font);
Context con = password.getContext();
Typeface face=Typeface.createFromAsset(con.getAssets(),"arial.ttf");
password.setTypeface(face);
Context con1 = forgot_password.getContext();
Typeface face1=Typeface.createFromAsset(con1.getAssets(),"arial.ttf");
forgot_password.setTypeface(face1);
// new theTask().execute();
login_button=(ImageButton)findViewById(R.id.login);
sign_button=(ImageButton)findViewById(R.id.signup);
login_button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
String username,password;
emailid =(EditText)findViewById(R.id.edemail);
epassword =(EditText)findViewById(R.id.edpassword);
username = emailid.getText().toString();
password = epassword.getText().toString();
showDialog(0);
// TODO Auto-generated method stub
SoapObject request=new SoapObject(NAMESPACE,METHOD_NAME);
String qry="{\"General\":"+"{\"type\": \"Request\","+"\"application\": \"Mmmmm\","+"\"appver\": \"1.0.0\","+"\"phoneDeviceID\": \"123456789\","+"\"deviceType\": \"Android\","+"\"deviceOSVersion\": \"3.0\"},"+"\"Login\":"+"{\"emailID\":"+"\""+username+"\","+"\"password\":"+"\""+password+"\""+"}"+"}";
Log.i("Input",qry);
request.addProperty("JSONRequestString",qry);
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.bodyOut=request;
envelope.encodingStyle=SoapSerializationEnvelope.ENC2001;
envelope.setOutputSoapObject(request);
AndroidHttpTransport androidHttpTransPort= new AndroidHttpTransport(URL);
try
{
try {
androidHttpTransPort.call(SOAP_ACTION,envelope);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SoapPrimitive rest=(SoapPrimitive)envelope.getResponse();
Log.i("output","Result"+rest );
// SoapObject var = (SoapObject)rest.getProperty(0);
String conv=rest.toString();
JSONObject js=new JSONObject(conv);
String login = js.getString("Login");
JSONObject err=new JSONObject(login);
String messcode=js.getString("HomePageFooterNewUpdates");
JSONObject code=new JSONObject(messcode);
int GetMessageCode=code.getInt("noOfMail");
Log.i("message code ","is " +GetMessageCode);
// String errc=err.getString("errorMsg");
// Log.i("err",errc);
int ResponseForLogin=err.getInt("errorCode");
Log.i("Response ","is "+ResponseForLogin);
if(ResponseForLogin==000){
Toast.makeText(Login.this, "Login Successfull", Toast.LENGTH_LONG).show();
// prepare the dialog box
/* ProgressDialog dialog = new ProgressDialog(this);
// make the progress bar Cancelable
dialog.setCancelable(true);
// set a message text
dialog.setMessage("Loading...");
// show it
dialog.show();*/
Intent i=new Intent(Login.this,Home.class);
i.putExtra("messcode", GetMessageCode);
startActivity(i);
} else {
Toast.makeText(Login.this, "Invalid Emailid or Password...Please Try Again", Toast.LENGTH_LONG).show();
}
}catch (XmlPullParserException e) {
e.printStackTrace();
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SoapFault e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} );
sign_button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Intent i=new Intent(Login.this, Signup.class);
startActivity(i);
}
});
}
}
Thanks in advance...
Just giving you few hints , try to take help from this.
ImageButton login=(ImageButton)findViewById(R.id.Login);
EditText editText1=(EditText)findViewById(R.id.emailText);
EditText editText2=(EditText)findViewById(R.id.passwordText);
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if((editText1.getText()+" ").trim().equals("") || editText1.getText() == null || (editText2.getText()+" ").trim().equals("") || editText2.getText() == null ){
//show error message here
}
else{
//perrform your action here
//either start a new activity or do something else
}
}
});
Hope this will help you.
I have found the following tutorial which has definitely helped me implement the correct login and registration screens using these resources:
Material Design
Shared Preferences
PHP scripts
MySQL Database
SQLlite Database
This is the link to the tutorial.
I know this is extremely late but I hope it can help you.

Categories

Resources