I created simple application which would login to DB and get data from it. But now I found a problem: If you in the first time write wrong login data and try to login second time it won't work. You have to restart it.
I think there is a problem in this code: EDITED
public class MyMoodleApplicationActivity extends Activity {
/** Called when the activity is first created. */
EditText username;
EditText password;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
username = (EditText)findViewById(R.id.username);
password = (EditText)findViewById(R.id.password);
final Button loginButton = (Button)findViewById(R.id.login);
loginButton.setOnClickListener(loginListener);
final Button clearButton = (Button)findViewById(R.id.clear);
clearButton.setOnClickListener(clearListener);
}
private OnClickListener loginListener = new OnClickListener(){
public void onClick(View v){
String usr = username.getText().toString();
String psw = password.getText().toString();
System.out.println("Username: "+usr);
System.out.println("Password: "+psw);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("usern",""+usr));
nameValuePairs.add(new BasicNameValuePair("passw",""+psw));
InputStream is = null;
String result = "";
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://ik.su.lt/*****");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
String usernameFromDB = "";
String firstnameFromDB = "";
String lastnameFromDB = "";
String emailFromDB = "";
String phoneFromDB = "";
String skypeFromDB = "";
String cityFromDB = "";
String descriptionFromDB = "";
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
usernameFromDB = json_data.getString("username");
firstnameFromDB = json_data.getString("firstname");
lastnameFromDB = json_data.getString("lastname");
emailFromDB = json_data.getString("email");
phoneFromDB = json_data.getString("phone1");
skypeFromDB = json_data.getString("skype");
cityFromDB = json_data.getString("city");
descriptionFromDB = json_data.getString("description");
System.out.println(usernameFromDB+ " " + firstnameFromDB+" "+lastnameFromDB+" "
+ emailFromDB + " " + phoneFromDB +" " + skypeFromDB+ " " + cityFromDB + " "+
descriptionFromDB);
}
}
catch(JSONException e){
AlertDialog alertDialog = new AlertDialog.Builder(MyMoodleApplicationActivity.this).create();
alertDialog.setTitle("Klaida!");
alertDialog.setMessage("Toks vartotojas neegzistuoja");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
return;
}
});
alertDialog.show();
Log.e("log_tag", "Error parsing data "+e.toString());
}
if(usr.length()== 0){
AlertDialog alertDialog = new AlertDialog.Builder(MyMoodleApplicationActivity.this).create();
alertDialog.setTitle("Klaida!");
alertDialog.setMessage("Jūs neįvedėte slapyvardžio");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
return;
}
});
alertDialog.show();
}
else if(psw.length()==0){
AlertDialog alertDialog = new AlertDialog.Builder(MyMoodleApplicationActivity.this).create();
alertDialog.setTitle("Klaida!");
alertDialog.setMessage("Jūs neįvedėte slaptažodžio");
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
return;
}
});
alertDialog.show();
}
else if (usr.equals(usernameFromDB)){
Intent in = new Intent(getApplicationContext(), LoggedUser.class);
in.putExtra("firstname", firstnameFromDB);
in.putExtra("lastname", lastnameFromDB);
in.putExtra("email", emailFromDB);
in.putExtra("phone1", phoneFromDB);
in.putExtra("skype", skypeFromDB);
in.putExtra("city", cityFromDB);
in.putExtra("description", descriptionFromDB);
startActivity(in);
finish();
}
}};
private OnClickListener clearListener = new OnClickListener(){
#Override
public void onClick(View v){
username.setText("");
password.setText("");
}
};
In these if statements I check if username and password you enter is empty username is not equal to the one in database.
How to rewrite the code that it would work?
Edited:
I have user john in DB but if I write John in login field and press login button it won't say that there is not the John user. And in LogCat I see that json stream is readed. Is there a way to set up a rule that upercase and lowercase letters would be different?
Related
Below is a registration form where user can register a new account, however when I try to sign up it connect to the server, but for some reason it failed to register!
with message from php file (Hmmm Look Like User Already Exist...) however I'm sure that the user doesn't exist in the database table!
RegisterActivity.java
public class RegisterActivity extends AppCompatActivity {
TextView sign_in_text;
EditText Name,Email,Pass,ConPass;
Button reg_button;
AlertDialog.Builder mBuilder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
sign_in_text = (TextView) findViewById(R.id.sign_in);
sign_in_text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(RegisterActivity.this,LoginActivity.class));
}
});
Name = (EditText) findViewById(R.id.user_name);
Email = (EditText) findViewById(R.id.email_register);
Pass = (EditText) findViewById(R.id.password_register);
ConPass = (EditText) findViewById(R.id.password_conf);
reg_button = (Button) findViewById(R.id.reg_button);
reg_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(Name.getText().toString().equals("")|| Email.getText().toString().equals("")|| Pass.getText().toString().equals("")){
mBuilder = new AlertDialog.Builder(RegisterActivity.this);
mBuilder.setTitle("Oops something went wrong!");
mBuilder.setMessage("Please fill all the fields");
mBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
AlertDialog alertDialog = mBuilder.create();
alertDialog.show();
}
else if (!(Pass.getText().toString().equals(ConPass.getText().toString()))){
mBuilder = new AlertDialog.Builder(RegisterActivity.this);
mBuilder.setTitle("Oops something went wrong!");
mBuilder.setMessage("Your passwords are not matching");
mBuilder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
Pass.setText("");
ConPass.setText("");
}
});
AlertDialog alertDialog = mBuilder.create();
alertDialog.show();
}
else {
BackgroundTask backgroundTask = new BackgroundTask(RegisterActivity.this);
backgroundTask.execute("register",Name.getText().toString(),Email.getText().toString(),Pass.getText().toString());
}
}
});
}
}
And this is the background task where I connect the to server
BackgroundTask.java
public class BackgroundTask extends AsyncTask<String, String, String> {
String register_url ="http://justawesome.net/ozone_registration/register.php";
String login_url ="http://justawesome.net/ozone_registration/login.php";
Context ctx;
ProgressDialog mProgressDialog;
Activity activity;
AlertDialog.Builder mBuilder;
public BackgroundTask(Context ctx){
this.ctx = ctx;
activity = (Activity) ctx;
}
#Override
protected void onPreExecute() {
mBuilder = new AlertDialog.Builder(activity);
mProgressDialog = new ProgressDialog(ctx);
mProgressDialog.setTitle("Please wait");
mProgressDialog.setMessage("Connecting to server....");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String method = params[0];
if (method.equals("register")){
try {
URL url = new URL(register_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter =new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String name = params[1];
String email = params[2];
String password = params[3];
String data = URLEncoder.encode("name", "UTF-8")+"-"+URLEncoder.encode(name,"UTF-8")+"&"+
URLEncoder.encode("email", "UTF-8")+"-"+URLEncoder.encode(email,"UTF-8")+"&"+
URLEncoder.encode("password", "UTF-8")+"-"+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line=bufferedReader.readLine()) != null){
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
Thread.sleep(5000);
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else if (method.equals("login")){
try {
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter =new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String email,password;
email = params[1];
password = params[2];
String data = URLEncoder.encode("email", "UTF-8")+"-"+URLEncoder.encode(email,"UTF-8")+"&"+
URLEncoder.encode("password", "UTF-8")+"-"+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line=bufferedReader.readLine()) != null){
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
Thread.sleep(5000);
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String json) {
mProgressDialog.dismiss();
try {
JSONObject jsonObject = new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
//JSONObject jsonObject = new JSONObject(json);
//String response = jsonObject.getString("server_response");
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
//JSONArray jsonArray = new JSONArray(response);
JSONObject Jo = jsonArray.getJSONObject(0);
String code = Jo.getString("code");
Log.d("code0", code);
String message = Jo.getString("message");
Log.d("message", message);
if(code.equals("reg_true")){
showDialog("Registration Success", message,code);
Log.d("code1", code);
}
else if(code.equals("reg_false")){
showDialog("Registration Failed", message,code);
Log.d("code2", code);
}
else if (code.equals("login_true")){
Intent intent = new Intent(activity, AccountActivity.class );
intent.putExtra("message", message);
activity.startActivity(intent);
}
else if (code.equals("login_false")){
showDialog("Login Error...",message,code);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
And this is the php file.
P.S.: I tested the backend and it works fine.
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
require "init.php";
$query = "SELECT * FROM userdb WHERE email like '$email';";
$result = mysqli_query($con,$query);
if (mysqli_num_rows($result)>0){
$response = array();
$code = "reg_false";
$message = "Hmmm Look Like User Already Exist...";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}
else{
$query = "INSERT INTO userdb(name,email,password)values('$name','$email','$password');";
$result = mysqli_query($con,$query);
if(!$result){
$response = array();
$code = "reg_false";
$message = "Some server error occourred. Try again... ";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}else{
$response = array();
$code = "reg_true";
$message = "Yuoohooo Registration Success... Thank you";
array_push($response,array("code"=>$code,"message"=>$message));
echo json_encode(array("server_response"=>$response));
}
}
mysqli_close($con);
?>
Appreciate your help
This question already has answers here:
How do I parse JSON in Android? [duplicate]
(3 answers)
Closed 5 years ago.
I am trying to implement login and signup form in Android with the help of JSON using post method. When i signup and enter the details it successfully register and data has been shown in my local host sever and when i login its enter wrong username and password its show incorrect details in toast and enter right details shows login success in toast, but i want when i enter right details its goes to another activity. and enter wrong details shows only toast. Here is the code :-
MainActivity.java
public class MainActivity extends Activity {
public static HashMap<Sound, MediaPlayer> SOUND_MAP=
new HashMap<Sound, MediaPlayer>();
public static int userScore= 0, computerScore=0,
buddyBoxId = 1, computerBoxId = 1;
public static Context CTX;
Button play;
private static final String TAG = "LoginActivity";
String URL = "http://10.0.2.2/test_android/index.php";
JSONParser jsonParser=new JSONParser();
ProgressDialog progressDialog;
TextView register_caption;
AdView adView = null;
private AdView mAdView;
EditText username, password;
Button btnSignIn, btnRegister;
ImageView fb;
int i=0;
private AdRequest adRequest;
InterstitialAd mInterstitialAd;
static MediaPlayer media;
static Handler mediaHandler;
public static int stat=0, totTurn = 0, maxEnd = 100;
public static SharedPreferences configs;
public static SharedPreferences.Editor configuration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.email);
password = (EditText)findViewById(R.id.passwordd);
btnSignIn = (Button) findViewById(R.id.play);
register_caption = (TextView) findViewById(R.id.register_caption);
fb = (ImageButton) findViewById(R.id.btnfb);
progressDialog = new ProgressDialog(this);
progressDialog.setCancelable(false);
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AttemptLogin attemptLogin = new AttemptLogin();
attemptLogin.execute(username.getText().toString(), password.getText().toString(), "");
}
});
register_caption.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent in = new Intent(MainActivity.this,Registration.class);
startActivity(in);
}
});
CTX = getApplicationContext();
configs = CTX. getSharedPreferences("snake_n_ladder", 0);
configuration = configs.edit();
loadConfig();
loadMedia();
}
private class AttemptLogin extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... args) {
String email = args[2];
String password = args[1];
String name = args[0];
ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", name));
params.add(new BasicNameValuePair("password", password));
if (email.length() > 0)
params.add(new BasicNameValuePair("email", email));
JSONObject json = jsonParser.makeHttpRequest(URL, "POST", params);
return json;
}
protected void onPostExecute(JSONObject result) {
// dismiss the dialog once product deleted
//Toast.makeText(getApplicationContext(),result,Toast.LENGTH_LONG).show();
try {
if (result != null) {
Toast.makeText(getApplicationContext(), result.getString("message"), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unable to retrieve any data from server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
JsonParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static JSONArray jArr = null;
static String json = "";
static String error = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
ArrayList<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method.equals("POST")){
// request method is POST
// defaultHttpClient
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
try {
Log.e("API123", " " +convertStreamToString(httpPost.getEntity().getContent()));
Log.e("API123",httpPost.getURI().toString());
} catch (Exception e) {
e.printStackTrace();
}
HttpResponse httpResponse = httpClient.execute(httpPost);
Log.e("API123",""+httpResponse.getStatusLine().getStatusCode());
error= String.valueOf(httpResponse.getStatusLine().getStatusCode());
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method.equals("GET")){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
Log.d("API123",json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
jObj.put("error_code",error);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
private String convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
return sb.toString();
}
}
protected void onPostExecute(JSONObject result) {
try {
if (result != null)
{
if(result.getString("message").equals("Successfully logged in"))
{
Intent intent = new Intent(ThisActivity.this,NewActivity.class);
startActivity(intent);
finish();
}
else
{
Toast.makeText(this,"Invalid credentials",Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getApplicationContext(), "Unable to retrieve any data from
server", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I'm facing problem in getting a response back in android from PHP.
First, it gets the right response in try then I don't know what cause problem it goes to catch and change response to null. My PHP files are perfectly working I tested them by giving default values.
Below is the code:
This class is used to connect to server and send data to PHP:
public class DatabaseFunctionality extends AsyncTask <String, String, String>{
int flag;
Context context;
String username;
String password;
String rname;
String city;
int mnum;
String sname;
String area;
String sadd;
int snum1;
int snum2;
String cpic;
String ppic;
Bitmap coverpic, profpic;
public String resp;
//public String r;
StringBuilder sb;
public DatabaseFunctionality(Context context, int f){
this.context=context;
this.flag=f;
}
#Override
protected String doInBackground(String... params) {
if(this.flag==0){
username=params[0];
password=params[1];
resp = login();
}
else if(this.flag==1){
rname = params[0];
username = params[1];
password = params[2];
city = params[3];
mnum = Integer.parseInt(params[4]);
sname = params[5];
area = params[6];
sadd = params[7];
snum1 = Integer.parseInt(params[8]);
snum2 = Integer.parseInt(params[9]);
resp = signup();
}
return resp;
}
public String login() {
try {
String link = "http://192.168.0.105:80/directdukan/login.php";
String data = URLEncoder.encode("username", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
sb.append(line);
break;
}
Log.e("string", sb.toString());
return sb.toString();
}
catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
public String signup(){
try{
String link = "http://192.168.0.105:80/directdukan/signup.php?rname="+rname+"&username="+username+"&password="+password+"&city="+city+"&mnum="+mnum+"&sname="+sname+"&area="+area+"&sadd="+sadd+"&sanum1="+snum1+"&snum2="+snum2;//+"& cpic="+coverpic+"& ppic="+profpic;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
Log.e("string", sb.toString());
return sb.toString();
} catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
public void addproduct(){
}
public void searchproduct(){
}
public void editproduct(){
}
public void deleteproduct(){
}
#Override
protected void onPostExecute(String result){
this.resp = result;
}
public Bitmap StringToBitMap(String encodedString){
try {
byte [] encodeByte=Base64.decode(encodedString, Base64.DEFAULT);
Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
} catch(Exception e) {
e.getMessage();
return null;
}
}
}
// Below LoginActivity & SignupActivity is used to get data from activity and send it to DatabaseFunctionality class
public class LoginActivity extends AppCompatActivity {
EditText username, password;
Button login, signup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.button_login);
signup = (Button) findViewById(R.id.button_signup);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String uname = username.getText().toString();
String pass = password.getText().toString();
if(!"".equals(uname) && !"".equals(pass)) {
DatabaseFunctionality db = new DatabaseFunctionality(LoginActivity.this,0);
db.execute(uname,pass);
if(db.resp.equals("user exist")) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_SHORT).show();
startActivity(intent);
}
else{
Toast.makeText(getApplicationContext(),"Username or Password is incorrect",Toast.LENGTH_LONG).show();
username.setText(null);
password.setText(null);
}
}
else {
Toast.makeText(getApplicationContext(), "Please Enter Username or Password", Toast.LENGTH_LONG).show();
username.setText(null);
password.setText(null);
}
}
});
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, SignupActivity.class);
startActivity(intent);
}
});
}
}
public class SignupActivity extends AppCompatActivity {
public int PICK_IMAGE_REQUEST = 1;
public Bitmap bitmap;
public Uri filePath;
String imgname;
EditText username, password, ownername, cnic, shopname, shopadd, shopphone, shopphone2, mobile;
TextView cpic, ppic;
Spinner citymenu, areamenu;
Button signup2, ucpic, uppic;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
ownername = (EditText) findViewById(R.id.rname);
shopname = (EditText) findViewById(R.id.shopname);
shopadd = (EditText) findViewById(R.id.shopadd);
shopphone = (EditText) findViewById(R.id.shopphone);
shopphone2 = (EditText) findViewById(R.id.shopphone2);
mobile = (EditText) findViewById(R.id.mobile);
citymenu =(Spinner) findViewById(R.id.citymenu);
areamenu = (Spinner) findViewById(R.id.areamenu);
cpic = (TextView) findViewById(R.id.coverpic);
ppic = (TextView) findViewById(R.id.profpic);
signup2 = (Button) findViewById(R.id.signup2);
ucpic = (Button) findViewById(R.id.uploadcpicb);
uppic = (Button) findViewById(R.id.uploadppicb);
ucpic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
imgname = getStringImage(bitmap);
cpic.setText(imgname);
}
});
uppic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
imgname = getStringImage(bitmap);
ppic.setText(imgname);
}
});
signup2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String uname = username.getText().toString();
String pass = password.getText().toString();
String rname = ownername.getText().toString();
String city = citymenu.getSelectedItem().toString();
String mnum = mobile.getText().toString();
String sname = shopname.getText().toString();
String area = areamenu.getSelectedItem().toString();
String sadd = shopadd.getText().toString();
String snum1 = shopphone.getText().toString();
String snum2 = shopphone2.getText().toString();
if(!"".equals(rname) && !"".equals(city) && !"".equals(uname) && !"".equals(pass) && !"".equals(sname) && !"".equals(mnum) && !"".equals(area) && !"".equals(sadd) && !"".equals(snum1)) {
DatabaseFunctionality db = new DatabaseFunctionality(SignupActivity.this, 1);
db.execute(rname,uname,pass,city,mnum,sname,area,sadd,snum1,snum2);
if(db.resp.equals("Signup Successful")) {
Intent intent = new Intent(SignupActivity.this, MainActivity.class);
startActivity(intent);
Toast.makeText(SignupActivity.this, "Signup Successful!",
Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(getApplicationContext(),"Fields with * are must",Toast.LENGTH_LONG).show();
}
}
else{
Toast.makeText(getApplicationContext(),"Fields with * are must",Toast.LENGTH_LONG).show();
}
}
});
String[] items = new String[]{"*Select","Abbottabad",
"Adezai",
"Ali Bandar",
"Amir Chah",
/* snip */
"Wazirabad",
"Yakmach",
"Zhob",
"Other"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items);
citymenu.setAdapter(adapter);
String[] items2 = new String[]{"*Select","Johar Town","Faisal Town", "Main Boulevard","Cantt","Model Town"};
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, items2);
areamenu.setAdapter(adapter2);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
}
So the scenario is I am trying to debug a simple application on my real device.I am using eclipse to make the application.
Now my application is communicating with a servlet which is on Server and application is running very smoothly in genymotion emulator(not using the emulator provided by eclipse). But when I try to run it in my device it is working perfectly till one activity class,but application is crashing on second activity.
So, after so many searches I am posting this question here. Hope I can find out any solution for this.
This is my Second Activity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.success);
Intent objIntent = getIntent();
s2 = objIntent.getStringExtra("repname");
findViewsById();
submit.setOnClickListener(this);
}
private void findViewsById() {
submit = (Button) findViewById(R.id.submit);
headerText = (TextView) findViewById(R.id.tv1);
headerText.setVisibility(View.INVISIBLE);
submit2 = (Button) findViewById(R.id.secondSubmit);
submit2.setVisibility(View.INVISIBLE);
t1= (TextView) findViewById(R.id.tvexample1);
t2= (TextView) findViewById(R.id.tvexample2);
submit2.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
//DO SOMETHING! {RUN SOME FUNCTION ... DO CHECKS... ETC}
lviewAdapter.clear();
lviewAdapter.notifyDataSetChanged();
Calendar cal = Calendar.getInstance();
System.out.println("what is from calendar"+cal);
Date currentLocalTime = cal.getTime();
//System.out.println("what is from CurrentLocalTime"+currentLocalTime);
DateFormat date = new SimpleDateFormat("yyyy-MM-dd");
date.setTimeZone(TimeZone.getTimeZone("GMT"));
//System.out.println("what is from date"+date);
String localTime = date.format(currentLocalTime);
//localTime = "2014-08-26";
System.out.println("and result is == " + localTime);
pb.setVisibility(View.VISIBLE);
new MyAsyncTask().execute(localTime,s2);
}
});
pb=(ProgressBar)findViewById(R.id.progressBar1);
pb.setVisibility(View.GONE);
c=this;
}
public void onClick(View view) {
Log.d("1:", "in the onclick");
Calendar cal = Calendar.getInstance();
System.out.println("what is from calendar"+cal);
Date currentLocalTime = cal.getTime();
//System.out.println("what is from CurrentLocalTime"+currentLocalTime);
DateFormat date = new SimpleDateFormat("yyyy-MM-dd");
date.setTimeZone(TimeZone.getTimeZone("GMT"));
//System.out.println("what is from date"+date);
String localTime = date.format(currentLocalTime);
//localTime = "2014-08-26";
System.out.println("and result is == " + localTime);
pb.setVisibility(View.VISIBLE);
new MyAsyncTask().execute(localTime,s2);
}
// #Override
// public void onBackPressed() {
// Log.d("CDA", "onBackPressed Called");
// Intent setIntent = new Intent(Intent.ACTION_MAIN);
// setIntent.addCategory(Intent.CATEGORY_HOME);
// setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// startActivity(setIntent);
// }
private class MyAsyncTask extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Log.d("tag1","in do in ");
String s=postData(params);
Log.d("tag2","in do in SSS ");
//Printing this 5 th
Log.d("what is s",s);
return s;
}
protected void onPostExecute(String result){
Log.d("on post ","on post execute");
pb.setVisibility(View.GONE);
Toast.makeText(getApplicationContext(),"Appointment Displayed", Toast.LENGTH_SHORT).show();
//Log.d("tag",result);
init(result);
submit.setVisibility(View.GONE);
headerText.setVisibility(View.VISIBLE);
submit2.setVisibility(View.VISIBLE);
}
}
protected void onProgressUpdate(Integer... progress){
pb.setProgress(progress[0]);
}
public String postData(String valueIWantToSend[]) {
String origresponseText="";
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("CurrentDate",valueIWantToSend[0]));
nameValuePairs.add(new BasicNameValuePair("repname", valueIWantToSend[1]));
System.out.println("CurrentDate"+valueIWantToSend[0]);
System.out.println("username"+valueIWantToSend[1]);
exampleString1= valueIWantToSend[0];
exampleString2= valueIWantToSend[1];
HttpClient httpclient = new DefaultHttpClient();
HttpParams params = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),10000000);
//httppost = new HttpPost("http://192.168.56.1:8080/First/Hello");
httppost = new HttpPost("http://203.199.134.131:8080/First/Hello");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
/* execute */
HttpResponse response = httpclient.execute(httppost);
System.out.println("response from servlet"+response.toString());
origresponseText=readContent(response);
Log.d("response", origresponseText);
}
catch (ClientProtocolException e) {
// TODO Auto-generated catch block
}
catch (IOException e) {
// TODO Auto-generated catch block
}
//removing unwated "" and other special symbols from response
String responseText = origresponseText.substring(1,origresponseText.length() -2 );
Log.d("Response tag", responseText);
return responseText;
}
// }
String readContent(HttpResponse response)
{
String text = "";
InputStream in =null;
try {
in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
//Log.d("", line);
sb.append(line + "\n");
//Printing this first
// Log.d("", line);
// Log.e("TAGpppp", ">>>>>PRINTING<<<<<");
// Log.e("TAGiiii", in.toString());
}
text = sb.toString();
Log.d("TEXT", text);
}
catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
in.close();
} catch (Exception ex) {
}
}
return text;
}
#SuppressWarnings("deprecation")
public void init(String result) {
System.out.println(result);
t1.setText(exampleString1);
t2.setText(exampleString2);
String response= result + "}";
System.out.println(response);
try {
JSONObject jsonArray = new JSONObject(response);
System.out.println("1:"+jsonArray);
//ArrayList obj1 = new ArrayList();
JSONArray obj1 = jsonArray.getJSONArray("get");
System.out.println("1:"+obj1);
for (int i = 0; i < obj1.length(); i++) {
System.out.println("Length of array"+obj1.length());
JSONObject results = obj1.getJSONObject(i);
System.out.println("2:"+results);
String pcode= results.getString("ProspCustCode");
System.out.println("Prospect code"+pcode);
String date= results.getString("FollowUpDate");
System.out.println("FollowUpDate"+date);
String time= results.getString("FollowUpTime");
System.out.println("FollowUpTime"+time);
String status= results.getString("Status");
System.out.println("Status"+status);
String ftype= results.getString("FollowUpType");
System.out.println("FollowUpType"+ftype);
String ntime= results.getString("NextFollowUpTime");
System.out.println("NextFollowUpTime"+ntime);
String cname= results.getString("ContactPerson");
System.out.println("ContactPerson"+cname);
String desig= results.getString("Designation");
System.out.println("Designation"+desig);
String com= results.getString("Comments");
System.out.println("Comments"+com);
String spoke= results.getString("SpokenTo");
System.out.println("SpokenTo"+spoke);
insertdata(pcode,date,time,status,ftype,ntime,cname,desig,com,spoke);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void insertdata(String PROSPCUSTCODE, String DATE, String TIME,
String STATUS, String FOLLOWUPTYPE, String NEXTFOLLOWUPTIME, String NAME,
String DESIGNATION, String COMMENTS, String SPOKENTO) {
HashMap<String, String> queryValues = new HashMap<String, String>();
queryValues.put("ProspCustCode", PROSPCUSTCODE);
queryValues.put("Date", DATE);
queryValues.put("Time", TIME);
queryValues.put("Status", STATUS);
queryValues.put("FollowUpType", FOLLOWUPTYPE);
queryValues.put("NextFollowUpTime", NEXTFOLLOWUPTIME);
queryValues.put("Name", NAME);
queryValues.put("Designation", DESIGNATION);
queryValues.put("Comments", COMMENTS);
queryValues.put("SpokenTo", SPOKENTO);
controller.insertDeails(queryValues);
//this.callHomeActivity(view);
DBController dbHelper = new DBController(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor cursor = newDB.rawQuery("SELECT * FROM TempFollowUpDetails", null);
if (cursor != null ) {
if (cursor.moveToFirst()) {
do {
System.out.println(cursor.getColumnIndex("ProspCustCode"));
//String ProspCustCode = c.getString(c.getColumnIndex("ProsCustCode"));
String Date = cursor.getString(cursor.getColumnIndex("Date"));
String Time = cursor.getString(cursor.getColumnIndex("Time"));
String Status = cursor.getString(cursor.getColumnIndex("Status"));
String NextFollowUpTime = cursor.getString(cursor.getColumnIndex("NextFollowUpTime"));
Name = cursor.getString(cursor.getColumnIndex("Name"));
System.out.println(cursor.getString(cursor.getColumnIndex("Name")));
String Designation = cursor.getString(cursor.getColumnIndex("Designation"));
String Comments = cursor.getString(cursor.getColumnIndex("Comments"));
String SpokenTo = cursor.getString(cursor.getColumnIndex("SpokenTo"));
String Id = cursor.getString(cursor.getColumnIndex("Id"));
//ProspCustCodeArray.add(ProspCustCode);
DateArray.add(Date);
TimeArray.add(Time);
StatusArray.add(Status);
NextFollowUpTimeArray.add(NextFollowUpTime);
NameArray.add(Name);
DesignationArray.add(Designation);
CommentsArray.add(Comments);
SpokenToArray.add(SpokenTo);
IdArray.add(Id);
}while (cursor.moveToNext());
}
displaylist(IdArray,NameArray);
}
System.out.println("Elements of name array"+NameArray);
System.out.println("Elements of name array"+DateArray);
System.out.println("Elements of name array"+TimeArray);
System.out.println("Elements of name array"+DesignationArray);
System.out.println("Elements of name array"+CommentsArray);
System.out.println("Elements of name array"+IdArray);
//............. For normal listview
}
private void displaylist(ArrayList<String> idArray2,
ArrayList<String> nameArray2) {
// TODO Auto-generated method stub
listView = (ListView) findViewById(R.id.listViewAnimals);
lviewAdapter = new ListCustomAdapter(this, idArray2, nameArray2);
System.out.println("adapter => "+lviewAdapter.getCount());
listView.setAdapter(this.lviewAdapter);
controller.deleteDetails(null);
//... start appointments details activity to show the details on item click listener
this.listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View viewClicked, int position, long id) {
TextView tv1 =(TextView)viewClicked.findViewById(R.id.lblListItem);
Intent intent = new Intent(Success.this, AppointmentDetails.class);
intent.putExtra("name", tv1.getText().toString());
startActivity(intent);
}
}); }
}
This is what my Log cat shows when asynctask is satrting after button click:
D/1:(15416): in the onclick
I/System.out(15416): what is from calendarjava.util.GregorianCalendar[time=1409392501700,areFieldsSet=true,lenient=true,zone=Asia/Calcutta,firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2014,MONTH=7,WEEK_OF_YEAR=35,WEEK_OF_MONTH=5,DAY_OF_MONTH=30,DAY_OF_YEAR=242,DAY_OF_WEEK=7,DAY_OF_WEEK_IN_MONTH=5,AM_PM=1,HOUR=3,HOUR_OF_DAY=15,MINUTE=25,SECOND=1,MILLISECOND=700,ZONE_OFFSET=19800000,DST_OFFSET=0]
I/System.out(15416): and result is == 2014-08-26
D/tag1(15416): in do in
I/System.out(15416): CurrentDate2014-08-26
I/System.out(15416): usernameaditi
I/System.out(15416): [socket][1] connection /203.199.134.131:8080;LocalPort=36598(10000000)
I/System.out(15416): [CDS]connect[/203.199.134.131:8080] tm:10000 D/Posix(15416): [Posix_connect Debug]Process com.example.simplehttpgetservlet :8080
I/System.out(22364): [socket][/192.168.2.73:45340] connected
I/System.out(15416): [CDS]rx timeout:0
W/System.err(15416): rto value is too small
I/System.out(15416): >doSendRequest
I/System.out(15416): <doSendRequest
I/System.out(15416): response from servletorg.apache.http.message.BasicHttpResponse#423611d8
If you use a real device you need to use the real IP of the server. Keep also in mind to open the required ports for your local network and connect your mobile with your local network via WiFi.
I'm not very familar with the secutity of servlets check also that you can connect to the server with a second computer too. (Depending on your configuration it is possible that you cannot access the server from outside of "localhost")
Who would of thought getting a dialog box to show would be so difficult. In C# it is so easy. I've looked all over line for help and every tip seems to cause me trouble than good. Can someone please look at the below code and tell me where I might have gone wrong?
What I want is very simple. User clicks button. Then list appears. Then user clicks on one of the items in list, and dialogue appears. The code in onItemClick in the listview event is from someone else. It apparently works for that person. I keep clicking and seeing nothing. I'm open to suggestions on how to fix it, or new code all together. Sorry, the log has no error messages.
Please be specific about where I put the code as I'm an Android noob. And thank you in advance!
public class SetPrediction extends Activity
{
Button btnInsrt, btnFTeam, btnSTeam;
ArrayList<NameValuePair> nameValuePairs;
TextView txtGameTeams;
Bundle recdData;
String game;
JSONArray jArray;
String result;
InputStream is;
StringBuilder sb;
ArrayList<String> fNames;
ListView listView;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.set_prediction);
nameValuePairs = new ArrayList<NameValuePair>();
txtGameTeams = (TextView) findViewById(R.id.txtGameTeams);
recdData = getIntent().getExtras();
game = recdData.getString("xxxx.xxxx.xxx");
txtGameTeams.setText("xxxxxxx: " + game + " game.");
btnInsrt = (Button) findViewById(R.id.btnInsert);
btnFTeam = (Button) findViewById(R.id.btnFirstTeam);
btnSTeam = (Button) findViewById(R.id.btnSecondTeam);
btnFTeam.setText(removeSpaces(game.split("vs")[0]));
btnSTeam.setText(removeSpaces(game.split("vs")[1]));
btnSTeam.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String result = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("players", removeSpaces(game.split("vs")[1])));
fNames = new ArrayList<String>();
listView = (ListView) findViewById(R.id.lstPlayerForPrediction);
//http post
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://xxxxx/getTeamPlayers.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection " + e.toString());
}
//parse json data
try
{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++)
fNames.add(jArray.getJSONObject(i).getString("First_Name"));
}
catch(JSONException e)
{
Log.e("log_tag", "Error parsing data " + e.toString());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(SetPrediction.this, android.R.layout.simple_list_item_1, fNames);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View predictView, int item, long arg3)
{
final CharSequence[] items = {"Online", "Away", "Do not distrub","Invisible","Offline"};
AlertDialog.Builder builder = new AlertDialog.Builder(SetPrediction.this);
builder.setTitle("Change Status");
builder.setItems(items, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int item)
{
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
});
}
public String removeSpaces(String s)
{
StringTokenizer st = new StringTokenizer(s," ",false);
String t="";
while (st.hasMoreElements()) t += st.nextElement();
return t;
}
The problem is in the listView.setOnItemClickListener(new OnItemClickListener() event. That the part that doesn't work.
Check out this:
public void showAlertDialog(String title, String message, Context context)
{
final AlertDialog alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle(title);
alertDialog.setMessage(message);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
Try using these code instead of your code just a minor change:::
AlertDialog.Builder builder = new AlertDialog.Builder(SetPrediction.this).create();
builder.setTitle("Change Status");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item){
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
}
});
builder.show();
also import the following :::
import android.app.AlertDialog;
import android.content.DialogInterface;