000webhost "0" value at username - android-studio

I connected my android studio program to a database with a login and register function.
Everytime I register my profile the username value is always "0" in the database.
Here's the code:
Register Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final EditText etAge = (EditText) findViewById(R.id.etAge);
final EditText etName = (EditText) findViewById(R.id.etName);
final EditText etUsername = (EditText) findViewById(R.id.etUsername);
final EditText etPassword = (EditText) findViewById(R.id.etPassword);
final Button bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String name = etName.getText().toString();
final String username = etUsername.getText().toString();
final String password = etPassword.getText().toString();
final int age = Integer.parseInt(etAge.getText().toString());
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(RegisterActivity.this, MainActivity.class);
RegisterActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
builder.setMessage("Register Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegisterRequest registerRequest = new RegisterRequest(name, username, age, password, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegisterActivity.this);
queue.add(registerRequest);
}
});
}
}
Register Request
public class RegisterRequest extends StringRequest{
private static final String REGISTER_REQUEST_URL = "http://animotradings.000webhostapp.com/Register.php";
private Map<String, String> params;
public RegisterRequest(String name, String username, int age, String password, Response.Listener<String> listener){
super(Method.POST, REGISTER_REQUEST_URL, listener, null);
params = new HashMap<>();
params.put("name", name);
params.put("username", username);
params.put("password", password);
params.put("age", age + "");
}
#Override
public Map<String, String> getParams() {
return params;
}
}
Register.php File
<?php
$con = mysqli_connect("localhost", "id52837_animotradings", "password", "id52837_animotradings");
$name = $_POST["name"];
$username = $_POST["username"];
$age = $_POST["age"];
$password = $_POST["password"];
$statement = mysqli_prepare($con, "INSERT INTO user (name, username, age, password) VALUES (?, ?, ?, ?)");
mysqli_stmt_bind_param($statement, "siss", $name, $username, $age, $password);
mysqli_stmt_execute($statement);
$response = array();
$response["success"] = true;
echo json_encode($response);?>

Related

Android Studio: How to send data from Activity to Fragment | Method invocation 'getString' may produce 'NullPointerException'

I am having a problem where in the Fragment the "getString()" says "Method invocation 'getString' may produce 'NullPointerException'" that's the only problem. The Fragment is stored in MainActivity in Navigation Window.
LoginActivity (Where MainActivity is getting the Data):
private void LoginMethod(String email, String password) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL, new Response.Listener() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String result = jsonObject.getString("success");
JSONArray jsonArray = jsonObject.getJSONArray("login");
if (result.equals("1")){
for (int i = 0; i < jsonArray.length(); i++){
JSONObject object = jsonArray.getJSONObject(i);
String username = object.getString("Username").trim();
String email = object.getString("Email").trim();
Toast.makeText(Login.this, "Login Success: " + username, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Login.this, MainActivity.class);
intent.putExtra("username", username);
intent.putExtra("email", email);
startActivity(intent);
}
}
else if (result.equals("0")) {
Toast.makeText(Login.this, "Login Failed" + result + response, Toast.LENGTH_LONG).show(); Log.e("JSON Error", response);
Log.e("Login Error", result);
}
}
catch (JSONException e){
Toast.makeText(Login.this, e.getMessage(), Toast.LENGTH_LONG).show();
Log.e("JSON Error", response);
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(Login.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Email", email);
params.put("Password", password);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
**MainActivity:**
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
Toolbar toolbar;
TextView getemail, getusername;
DrawerLayout drawerLayout;
NavigationView navigationView;
View navheader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("State","onCreate");
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawerLayout = findViewById(R.id.drawerLayout);
navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navheader = navigationView.getHeaderView(0);
String getUsername = getIntent().getStringExtra("username");
String getEmail = getIntent().getStringExtra("email");
getusername = navheader.findViewById(R.id.getusername);
getemail = navheader.findViewById(R.id.getemail);
toolbar.setTitle(getUsername);
getusername.setText(getUsername);
getemail.setText(getEmail);
ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.nav_drawer_open, R.string.nav_drawer_close);
drawerLayout.addDrawerListener(actionBarDrawerToggle);
actionBarDrawerToggle.syncState();
if (savedInstanceState == null){
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new Home()).commit();
navigationView.setCheckedItem(R.id.home);
}
}
public void getAccountFragmentData(){
String test = "akshdasjkdhsajkdasdas";
String test2 = "wadahawawaawaww";
Bundle bundle = new Bundle();
bundle.putString("username", test);
bundle.putString("email", test2);
Account account = new Account();
account.setArguments(bundle);
Toast.makeText(this, "Account", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.home:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new Home()).commit();
break;
case R.id.orderfood:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FoodOrder()).commit();
break;
case R.id.account:
getAccountFragmentData();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new Account()).commit();
break;
case R.id.settings:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new Settings()).commit();
break;
case R.id.email:
Toast.makeText(this, "Email", Toast.LENGTH_SHORT).show();
break;
case R.id.share:
Toast.makeText(this, "Share", Toast.LENGTH_SHORT).show();
break;
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(GravityCompat.START)){
drawerLayout.closeDrawer(GravityCompat.START);
}
else {
super.onBackPressed();
}
}
#Override
protected void onStart() {
super.onStart();
Log.i("State","onStart");
}
#Override
protected void onResume() {
super.onResume();
Log.i("State","onResume");
}
#Override
protected void onPause() {
super.onPause();
Log.i("State","onPause");
}
#Override
protected void onStop() {
super.onStop();
Log.i("State","onStop");
}
#Override
protected void onRestart() {
super.onRestart();
Log.i("State","onRestart");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.i("State","onDestroy");
}
}
**Fragment:
**
public class Account extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_account, container, false);
TextView getUsername = v.findViewById(R.id.username);
TextView getEmail = v.findViewById(R.id.email);
Bundle bundle = this.getArguments();
String setUsername = bundle.getString("username");
String setEmail = bundle.getString("email");
getUsername.setText(setUsername);
getEmail.setText(setEmail);
Log.i("Data Sent", "Sent");
return v;
}
I want the Fragment to get the data from MainActivity.

SQL Server - Login failed for user (Android Studio)

I have written code using JDBC to create registration page in Android Studio. I create database in SQL Server 2019. In addition I tried to connect from the code to MSSQL database and insert values, but while I run the app I'm getting the error:
login failed for user.
I have examined many options that can cause this error and I fixed them. For example: The server authentication is SQL Server authentication,the TCP option at the server is enabled, I have the relevant permissions of the user, also I check the if the firewall is the cause for this error. However, I continue to receive the error.
The connection class:
public class ConnectionClass {
public static String ip= "***.***.*.*:1433"; //
public static String user_name ="****";
public static String password = "****";
public static String database = "tests";
}
The Registeration class:
EditText email;
EditText password;
EditText confirmPassword;
Button sign_up;
EditText name;
Connection connection1;
Statement statement;
TextView status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sign_up_parent);
email = (EditText) findViewById(R.id.editTextTextEmailAddress2);
password = (EditText) findViewById(R.id.editTextTextPassword);
confirmPassword = (EditText) findViewById(R.id.editTextTextPassword2);
sign_up = (Button) findViewById(R.id.button);
name = (EditText) findViewById(R.id.editTextTextPassword3);
status = (TextView) findViewById(R.id.status);
sign_up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new ParentSignUp.registerUser().execute("");
}
});
}
public class registerUser extends AsyncTask<String, String, String>{
String z ="";
Boolean isSuccess = false;
public registerUser() {
super();
}
#Override
protected void onPreExecute() {
status.setText("Sending Data to Database");
}
#Override
protected void onPostExecute(String s) {
name.setText("");
email.setText("");
password.setText("");
confirmPassword.setText("");
}
#Override
protected String doInBackground(String... strings) {
try {
connection1 = connection_class(ConnectionClass.user_name.toString(), ConnectionClass.password.toString(),
ConnectionClass.database.toString(), ConnectionClass.ip.toString());
if (connection1 == null) {
z = "Check Internet Connection";
}
else {
String sql = "INSERT INTO test (name,password, email) VALUES ('example', 'example', 'example')";
statement = connection1.createStatement();
statement.executeUpdate(sql);
}
}
catch (Exception e) {
isSuccess = false;
z = e.getMessage();
}
return null;
}
}
#SuppressLint("NewApi")
public Connection connection_class (String user, String password, String database, String server) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Connection connection = null;
String connectionUrl = null;
try{
Class.forName("net.sourceforge.jtds.jdbc.Driver");
connectionUrl = "jdbc:jtds:sqlserver://" + server + "/" + database + ";user=" + user + ";"+"password=" + password + ";";
connection = DriverManager.getConnection(connectionUrl);
}catch (Exception e){
Log.e("SQL Connection Error : ", e.getMessage());
}
return connection;
}

getting error when getting array data with where condition from MYSQL in android

I want to get all data which is available with the specific username from the table in listview using adapter.
I got error "org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject".
below is code
PHP file is working perfectly. I get all data which is available with the specified username.
ExpenseList.php
<?php
require_once("Config.php");
$response = array();
if(isset($_GET['apicall'])){
switch($_GET['apicall']){
case 'expense':
if(isTheseParametersAvailable(array('username'))){
$username = $_POST['username'];
$stmt = $con->prepare("SELECT * FROM Expense_Master WHERE VV_User_Name = '$username' ORDER BY VD_Expense_Date ASC");
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows > 0){
$stmt->bind_result($expenseid, $userid, $username, $entrydate, $expensedate, $credit, $debit, $description, $modifieddate);
$products = array();
while($stmt->fetch()){
$temp = array();
$temp['expenseid'] = $expenseid;
$temp['userid'] = $userid;
$temp['username'] = $username;
$temp['entrydate'] = $entrydate;
$temp['expensedate'] = $expensedate;
$temp['credit'] = $credit;
$temp['debit'] = $debit;
$temp['description'] = $description;
$temp['modifieddate'] = $modifieddate;
array_push($products, $temp);
$response['error'] = false;
$response['message'] = 'Fetch successfull';
}
}else{
$response['error'] = false;
$response['message'] = 'Invalid username';
}
}
break;
$response['error'] = true;
$response['message'] = 'Invalid Operation Called';
}
}else{
$response['error'] = true;
$response['message'] = 'Invalid API Call';
}
echo json_encode($response);
echo json_encode($products);
function isTheseParametersAvailable($params){
foreach($params as $param){
if(!isset($_POST[$param])){
return false;
}
}
return true;
}
?>
Here is ExpenseList.JAVA
private static final String EXPENSE_URL = "http:server.com/ExpenseList.php?apicall=expense";
private List<ExpenseListNotes> userNotes = new ArrayList<>();
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_expense_list);
spinnerUserNotes = new ArrayList<SpinnerUserNotes>();
expenseData();
}
private void expenseData() {
//if everything is fine
class expenseData extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
JSONArray array = new JSONArray(s);
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject product = array.getJSONObject(i);
userNotes.add(new ExpenseListNotes(
product.getInt("expenseid"),
product.getString("userid"),
product.getString("username"),
product.getString("entrydate"),
product.getString("expensedate"),
product.getString("credit"),
product.getString("debit"),
product.getString("description")));
}
ExpenseListAdapter adapter = new ExpenseListAdapter(ExpenseList.this, userNotes);
listView.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error : "+e.toString(), Toast.LENGTH_LONG).show();
Log.e("Error", e.toString());
}
}
#Override
protected String doInBackground(Void... voids) {
//creating request handler object
RequestHandler requestHandler = new RequestHandler();
//creating request parameters
HashMap<String, String> params = new HashMap<>();
params.put("username", "Alpesh");
//returing the response
return requestHandler.sendPostRequest(URL_EXPENSE, params);
}
}
expenseData ul = new expenseData();
ul.execute();
}
Here is AdapterClass
private class ExpenseListAdapter extends BaseAdapter
{
private Context context;
private List<ExpenseListNotes> invoiceModelArrayList;
public ExpenseListAdapter(Context context, List<ExpenseListNotes> invoiceModelArrayList) {
this.context = context;
this.invoiceModelArrayList = (List<ExpenseListNotes>) invoiceModelArrayList;
}
#Override
public int getCount() {
return invoiceModelArrayList.size();
}
#Override
public Object getItem(int i) {
return invoiceModelArrayList.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(final int i, View v, ViewGroup viewGroup)
{
final ViewHolder holder;
ButterKnife.bind(this, v);
if (v == null)
{
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.row_expense_list, null, true);
holder.tvRELUserid = v.findViewById(R.id.tvRELUserid);
holder.tvRELExpenseID = v.findViewById(R.id.tvRELExpenseID);
holder.tvRELUsername = v.findViewById(R.id.tvRELUsername);
holder.tvRELCredit = v.findViewById(R.id.tvRELCredit);
holder.tvRELDebit = v.findViewById(R.id.tvRELDebit);
holder.tvRELExpenseDate = v.findViewById(R.id.tvRELExpenseDate);
holder.tvRELEntryDate = v.findViewById(R.id.tvRELEntryDate);
holder.tvRELDescription = v.findViewById(R.id.tvRELDescription);
holder.btnDelete = v.findViewById(R.id.btnRELDelete);
holder.btnUpdate = v.findViewById(R.id.btnRELUpdate);
v.setTag(holder);
}
else
{
holder = (ViewHolder)v.getTag();
}
holder.tvRELExpenseID.setText(String.valueOf(invoiceModelArrayList.get(i).getExpenseID()));
holder.tvRELUserid.setText(String.valueOf(invoiceModelArrayList.get(i).getUserID()));
holder.tvRELUsername.setText(String.valueOf(invoiceModelArrayList.get(i).getUsername()));
holder.tvRELCredit.setText(String.valueOf(invoiceModelArrayList.get(i).getCredit()));
holder.tvRELDebit.setText(String.valueOf(invoiceModelArrayList.get(i).getDebit()));
holder.tvRELExpenseDate.setText(String.valueOf(invoiceModelArrayList.get(i).getExpenseDate()));
holder.tvRELEntryDate.setText(String.valueOf(invoiceModelArrayList.get(i).getEntryDate()));
holder.tvRELDescription.setText(String.valueOf(invoiceModelArrayList.get(i).getDescription()));
return v;
}
public void setFilter(List<ExpenseListNotes> newList)
{
invoiceModelArrayList = new ArrayList<>();
invoiceModelArrayList.addAll(newList);
notifyDataSetChanged();
}
}
private class ViewHolder {
TextView tvRELUserid, tvRELExpenseID, tvRELUsername, tvRELCredit, tvRELDebit, tvRELExpenseDate, tvRELEntryDate, tvRELDescription;
Button btnDelete, btnUpdate;
}
Code for RequestHandler.Class
public class RequestHandler
{
public String sendPostRequest(String requestURL, HashMap<String, String> postDataParams)
{
URL url;
StringBuilder sb = new StringBuilder();
try
{
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
sb = new StringBuilder();
String response;
while ((response = br.readLine()) != null) {
sb.append(response);
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
return sb.toString();
}
//this method is converting keyvalue pairs data into a query string as needed to send to the server
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet())
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
Where am I doing wrong?

Loading image from URL to ListView

I am trying to make a list view. I did it successfully without the photos loading from url without using a custom array adapter. However how can I implement loading images from url without using a custom array adapter?
I am trying to use the working codes from this thread but it is giving an error for holder.
Error Part
icon = new ImageDownloaderTask(holder.imageView).execute(doctorPhoto);
DoctorsActivity.java
public class DoctorsActivity extends AppCompatActivity {
private JSONArray arrayAdapter;
private static final String URL_FOR_BALANCE = "http://192.168.1.28/api2/doctors.php";
String cancel_req_tag = "login";
private ListView lv;
ArrayList<HashMap<String, String>> contactList;
Bitmap icon = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctors);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.toolbar_doctors);
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#003764")));
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
final String pid = sharedPreferences.getString(Config.UID_SHARED_PREF, null);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
StringRequest strReq = new StringRequest(Request.Method.POST,
URL_FOR_BALANCE, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
JSONArray contacts = jObj.getJSONArray("user");
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
String doctorTitle = c.getString("title");
String doctorName = c.getString("first_name");
String doctorSurname = c.getString("last_name");
String doctorPhoto = c.getString("photo"); //image URL
String doctorMobile = c.getString("mobile");
String doctorFullName = doctorTitle+" "+doctorName+" "+doctorSurname;
icon = new ImageDownloaderTask(holder.imageView).execute(doctorPhoto);
// tmp hash map for single contact
HashMap<String, String> contact = new HashMap<>();
// adding each child node to HashMap key => value
contact.put("photo", icon);
contact.put("doctor", doctorFullName);
contact.put("mobile", doctorMobile);
// adding contact to contact list
contactList.add(contact);
}
ListAdapter adapter = new SimpleAdapter(
DoctorsActivity.this, contactList,
R.layout.activity_doctors_list_item, new String[]{"photo", "doctor",
"mobile"}, new int[]{R.id.photo,
R.id.doctor, R.id.mobile});
lv.setAdapter(adapter);
} else {
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to login url
Map<String, String> params = new HashMap<String, String>();
params.put("uid", pid);
params.put("lang", Locale.getDefault().getDisplayLanguage());
return params;
}
};
// Adding request to request queue
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(strReq,cancel_req_tag);
}
class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
public ImageDownloaderTask(ImageView imageView) {
imageViewReference = new WeakReference<ImageView>(imageView);
}
#Override
protected Bitmap doInBackground(String... params) {
return downloadBitmap(params[0]);
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
if (bitmap != null) {
imageView.setImageBitmap(bitmap);
} else {
Drawable placeholder = null;
imageView.setImageDrawable(placeholder);
}
}
}
}
private Bitmap downloadBitmap(String url) {
HttpURLConnection urlConnection = null;
try {
URL uri = new URL(url);
urlConnection = (HttpURLConnection) uri.openConnection();
final int responseCode = urlConnection.getResponseCode();
if (responseCode != HttpURLConnection.HTTP_OK) {
return null;
}
InputStream inputStream = urlConnection.getInputStream();
if (inputStream != null) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}
} catch (Exception e) {
urlConnection.disconnect();
Log.w("ImageDownloader", "Errore durante il download da " + url);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
}
}
Why not use a 3rd party lib like https://github.com/bumptech/glide?
Relevant code:
// ...
new Glide
.with(convertView.getContext())
.load(url)
.centerCrop()
.placeholder(R.drawable.noimage)
.crossFade()
.into(bmImage);
holder.tvName.setText(doctorList.get(position).getName());
holder.tvMobile.setText(doctorList.get(position).getMobile());
// ...
For everyone who wants to have listView with images this my corrected working Custom Adapter:
public class DoctorAdapter extends ArrayAdapter<Doctors>{
ArrayList<Doctors> doctorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public DoctorAdapter(Context context, int resource, ArrayList<Doctors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
doctorList = objects;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.photo);
holder.tvName = (TextView) v.findViewById(R.id.doctor);
holder.tvMobile = (TextView) v.findViewById(R.id.mobile);
holder.callButton = (Button) v.findViewById(R.id.btnCall);
holder.callButton.setTag(holder);
holder.callButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ViewHolder viewHolder = (ViewHolder) view.getTag();
String message= viewHolder.tvMobile.getText().toString();
Toast.makeText(view.getContext(), message, Toast.LENGTH_SHORT).show();
}
});
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.noimage);
new DownloadImageTask(holder.imageview).execute(doctorList.get(position).getImage());
holder.tvName.setText(doctorList.get(position).getName());
holder.tvMobile.setText(doctorList.get(position).getMobile());
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView tvName;
public TextView tvMobile;
public Button callButton;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}

login form validation in android before implementing method login

I need help to filter empty edittext in login activity before trying to call method and execute query in mysql.. I am new in android development and getting really lost.. I followed a tutorial that works well in registration and login but no filtering or validation. Sad to say, I was not able to fully understand the steps on how each function / method are running.. I will appreciate if you can give me a link to a better page for a good tutorial which is not obsolete or have deprecated libraries.. I am using android 1.5.
I've been searching google and threads here but I could not find solution that is understandable by a newbie in android..
Here is the code of my Main.java which handles log in
public class Main extends AppCompatActivity implements View.OnClickListener {
EditText name, password;
String Name, Password;
Context ctx=this;
String NAME=null, PASSWORD=null, EMAIL=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
name = (EditText) findViewById(R.id.main_name);
password = (EditText) findViewById(R.id.main_password);
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();
}
});
}
public void main_register(View v){
startActivity(new Intent(this,Register.class));
}
public void main_login(View v){
Name = name.getText().toString();
Password = password.getText().toString();
BackGround b = new BackGround();
b.execute(Name, Password);
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.main_login:
break;
}
}
class BackGround extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String name = params[0];
String password = params[1];
String data="";
int tmp;
try {
URL url = new URL("http://10.0.2.2/BirdBreedingManagement/scripts/login.php");
String urlParams = "name="+name+"&password="+password;
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);
OutputStream os = httpURLConnection.getOutputStream();
os.write(urlParams.getBytes());
os.flush();
os.close();
InputStream is = httpURLConnection.getInputStream();
while((tmp=is.read())!=-1){
data+= (char)tmp;
}
is.close();
httpURLConnection.disconnect();
return data;
} catch (MalformedURLException e) {
e.printStackTrace();
return "Exception: "+e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "Exception: "+e.getMessage();
}
}
#Override
protected void onPostExecute(String s) {
String err=null;
try {
JSONObject root = new JSONObject(s);
JSONObject user_data = root.getJSONObject("user_data");
NAME = user_data.getString("name");
PASSWORD = user_data.getString("password");
EMAIL = user_data.getString("email");
} catch (JSONException e) {
e.printStackTrace();
err = "Exception: "+e.getMessage();
}
Intent i = new Intent(ctx, Home.class);
i.putExtra("name", NAME);
i.putExtra("password", PASSWORD);
i.putExtra("email", EMAIL);
i.putExtra("err", err);
startActivity(i);
}
}
And here is the php script
try{
//$username = "jeel";
//$pssword = "23456";
$username = filter_input(INPUT_POST, 'name');
$pssword = filter_input(INPUT_POST, 'password');
if($username == "" ){
$results = "Invalid Entry";
echo json_encode(array("user_data"=>$results));
}else{
$stmt = $db->prepare('SELECT * '
. 'FROM users1 '
. 'WHERE name = :uname AND password = :password ');
$stmt->bindParam(':uname', $username);
$stmt->bindParam(':password', $pssword);
$stmt->execute();
$results = $stmt->fetch(PDO::FETCH_ASSOC);
if($results > 0 ){
$response = array();
echo json_encode(array("user_data"=>$results));
} else{
$results = "No Record Found";
echo json_encode(array("user_data"=>$results));
}
}
}catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
Thanks in advance.
Since you need to check the username and password fields empty or not before running the AsyncTask to get data from php. Modify the main_login(View v) method as below
public void main_login(View v){
Name = name.getText().toString();
Password = password.getText().toString();
if(Name==null || Password==null){
// can alert the user that either one of username or the password is empty by
Toast.makeText(getActivity(), "Username or the Password is empty",Toast.LENGTH_LONG).show();
// in here you can restart the current activity
startActivity(this,Main.class);
finish(); // to destroy the current activity
}
else{
BackGround b = new BackGround();
b.execute(Name, Password);
}
}
The answer of Kasun Siyambalapitiya lead me to make the code perform as expected with some adjustment made.. I am posting it here to share to others who's also looking for a code which they can try if the answer of Kasun didn't fit in their requirement..
`public void main_login(View v){
Name = name.getText().toString();
Password = password.getText().toString();
if(name.getText().length()==0){
Toast.makeText(getApplicationContext(),
"Please Enter your name", Toast.LENGTH_LONG).show();
Intent intent = getIntent();
startActivity(intent);
}else{
Intent intent = getIntent();
startActivity(intent);
BackGround b = new BackGround();
b.execute(Name, Password);
}
}`
I remove the finish command to avoid the application from closing and reopening.

Resources