Android going to 'else' even when result matches the if statement - android

I am developing an android app.
In a specific part of my code, the else option is always executed, even though the if statement is satisfied. Any help is highly appreciated.
Here is my code:
PHP:
<?php
error_reporting(0);
include 'conexao.php';
$usuario = $_POST["username"];
$senha = $_POST["password"];
$result = mysql_query("select * from login where usuario = '" . $usuario . "' and senha = '" . $senha . "';");
$num_rows = mysql_num_rows($result);
if ($num_rows == 0) {
echo 'false';
} else if ($num_rows == 1) {
echo 'true';
} else {
echo 'nenhum';
}
?>
and my Java :
EditText txtusuario, txtsenha;
Button btnlogin;
public static final int CONNECTION_TIMEOUT=10000;
public static final int READ_TIMEOUT=15000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
txtusuario = (EditText) findViewById(R.id.txtusuario);
txtsenha = (EditText) findViewById(R.id.txtsenha);
btnlogin = (Button) findViewById(R.id.btnlogin);
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Get text from email and passord field
final String username = txtusuario.getText().toString();
final String password = txtsenha.getText().toString();
// Initialize AsyncLogin() class with email and password
new AsyncLogin().execute(username,password);
}
});
}
private class AsyncLogin extends AsyncTask<String, String, String>
{
ProgressDialog pdLoading = new ProgressDialog(LoginActivity.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url = new URL("http://rhynotcc.hol.es/teste/login.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "exception";
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection)url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// Append parameters to URL
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("username", params[0])
.appendQueryParameter("password", params[1]);
String query = builder.build().getEncodedQuery();
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "exception";
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return(result.toString());
} else {
return("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return "exception";
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
String teste = "true";
if(result.equals(teste)) {
//Notificação para saber o resultado do login
int a = 0;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(LoginActivity.this);
mBuilder.setSmallIcon(R.drawable.escavadeira);
mBuilder.setContentTitle("Notificação");
mBuilder.setContentText("Conexão deu certo caralho" + result);
NotificationManager mNot = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNot.notify(a, mBuilder.build());
} else {
int a = 0;
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(LoginActivity.this);
mBuilder.setSmallIcon(R.drawable.escavadeira);
mBuilder.setContentTitle("Notificação");
mBuilder.setContentText("Deu errado" + result);
NotificationManager mNot = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNot.notify(a, mBuilder.build());
}
}
}
the result in my notification is 'deu errado true' when true should been the if statement, and I have already tried result.equals("true")

if ($num_rows == 0) {
echo 'false';
} else if ($num_rows == 1) {
echo 'true';
} else {
echo 'nenhum';
}
instead of this make sure your code should be just like
if ($num_rows) {
echo 'false';
} else {
echo 'nenhum';
}

#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//this method will be running on UI thread
pdLoading.dismiss();
String teste = "true";
int a = 0;
NotificationCompat.Builder mBuilder = new
NotificationCompat.Builder(LoginActivity.this);
mBuilder.setSmallIcon(R.drawable.escavadeira);
mBuilder.setContentTitle("Notificação");
if (result.equals(teste)) {
//Notificação para saber o resultado do login
mBuilder.setContentText("Conexão deu certo caralho" + result);
} else {
mBuilder.setContentText("Deu errado" + result);
}
NotificationManager mNot = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNot.notify(a, mBuilder.build());
}

Related

Android : take Data in ListView

Actually in my project, I'm blocked. So, for the first time I ask the community of Stackoverflow. I'm new in development.
So, I have a MySql with my datas and I wan't to see in my application the items of users.
For that, I've this :
public class SuccessActivity extends AppCompatActivity {
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private ListView listView;
protected String meubles[] = new String[100];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_success);
Intent intent = getIntent();
String id = intent.getStringExtra("id");
this.listView = (ListView) findViewById(R.id.liste);
new SuccessActivity.Recup().execute(id);
}
//PRIVATE CLASSE POUR AFFICHER LES MEUBLES
private class Recup extends AsyncTask<String, String, String> {
HttpURLConnection conn;
URL url = null;
#Override
protected String doInBackground(String... params) {
try {
//url d'ou reside mon fichier php
url = new URL("http://opix-dev.fr/mytinyhomme/personne/afficher.meuble.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "exception";
}
try {
// parametrage du HttpURLConnection pour recevoir et envoyer des donner à mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// Append parameters to URL
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("id", params[0]);
String query = builder.build().getEncodedQuery();
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return "exception";
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return ("unsuccessful");
}
} catch (IOException e) {
e.printStackTrace();
return "exception";
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String resulta) {
//this method will be running on UI thread
if (resulta.equalsIgnoreCase("false")) {
} else if (resulta.equalsIgnoreCase("exception") || resulta.equalsIgnoreCase("unsuccessful")) {
} else {
try {
JSONArray nom = new JSONArray(resulta);
System.out.println(nom);
String meubles[] = new String[100];
for (int i = 0; i < nom.length(); i++){
JSONObject jsonobject = nom.getJSONObject(i);
meubles[i]= jsonobject.getString("nom");
System.out.println(jsonobject);
System.out.println(meubles);
item.setText( meubles[i]);
}
System.out.println(meubles);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
The file.php is correct because the JSONArray in System.print is ok But I've try with some TextView for display the board at the end, but I did not succeed.
How I can use the meuble[0] , meuble[1], meuble[2](it's board of String name of items) in a ListView ?
Here is what you need to do to show your data in a listview,
Modified onPostExecute() method:
#Override
protected void onPostExecute(String resulta) {
//this method will be running on UI thread
if (resulta.equalsIgnoreCase("false")) {
} else if (resulta.equalsIgnoreCase("exception") || resulta.equalsIgnoreCase("unsuccessful")) {
} else {
try {
JSONArray nom = new JSONArray(resulta);
System.out.println(nom);
String meubles[] = new String[100];
for (int i = 0; i < nom.length(); i++){
JSONObject jsonobject = nom.getJSONObject(i);
meubles[i]= jsonobject.getString("nom");
System.out.println(jsonobject);
System.out.println(meubles);
}
ArrayAdapter<String> listAdapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,meubles);
listView.setAdapter(listAdapter);
System.out.println(meubles);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
What's added?
You need an adapter to show items in a listview. You can create your custom adapter class by extending an arrayadapter or you can use an arrayadapter without customizing it as shown.
Added code:
Create a new adapter,
ArrayAdapter listAdapter=new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,list);
Set adapter for your listview,
listView.setAdapter(listAdapter);

RecyclerView Pagination not maintaining Scroll Position

I am a newbie in android and I've been working around pagination with recyclercview. I am receiving my data from a server(running php) and returning it in a JSON format which brings the data in bunches like 1-10, 11-20... so on. I call notifyDataSetChanged with this. But the problem is recyclerview scrolls back to the top when retrieving more data instead of retaining the current position. How do I go about this?
When scrollbar gets to the bottom, it triggers the asynctask
AsynTask:
public class LoadRecharge extends AsyncTask<String, String, String> {
private boolean socketTimeout = false;
Context context;
public static final String TAG = "custom_message";
public AsyncResponse delegate = null;
private String server_url = "https://blockgator.com/mobile/endless.php";
public LoadRecharge(Context ctxt, AsyncResponse asyncResponse) {
delegate = asyncResponse;
context = ctxt;
}
#Override
protected String doInBackground(String... params) {
if (connectGoogle()) {
String post_data = "";
try {
URL url = new URL(server_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"));
post_data = URLEncoder.encode("page", "UTF-8") + "=" + URLEncoder.encode(params[0], "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
Log.e(TAG, "error: " + e.getMessage());
}
} else {
this.socketTimeout = true;
}
return null;
}
#Override
protected void onPreExecute() {
arr.add(null);
scrollAdapter.notifyItemInserted(arr.size() - 1);
}
#Override
protected void onPostExecute(String result) {
arr.remove(arr.size() - 1);
scrollAdapter.notifyItemRemoved(arr.size());
if (this.socketTimeout) {
Toast.makeText(context, "unable to connect to server", Toast.LENGTH_SHORT).show();
} else {
delegate.processFinish(result);
}
}
public boolean connectGoogle() {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setConnectTimeout(3000);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
#Override
public void processFinish(String output) {
try {
JSONObject jsonObject = new JSONObject(output);
if (jsonObject.get("status").toString().equals("success")) {
JSONArray jsonarr = jsonObject.getJSONArray("data");
String columns[] = {"id", "bill_amount", "bill_price", "variation"};
for (int i = 0; i < jsonarr.length(); i++) {
ArrayList<String> temp = new ArrayList<>();
for (String column : columns) {
temp.add(jsonarr.getJSONObject(i).getString(column));
}
arr.add(temp);
setAdapter(arr);
}
} else if (jsonObject.get("status").toString().equals("end")) {
total = "end";
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(this, "exception from json", Toast.LENGTH_LONG).show();
} catch (NullPointerException e) {
Toast.makeText(this, "Unable to connect to server...", Toast.LENGTH_LONG).show();
Toast.makeText(this, "Null from json", Toast.LENGTH_LONG).show();
}
}
public void setAdapter(ArrayList<ArrayList<String>> arr) {
recycler.setAdapter(scrollAdapter);
scrollAdapter.notifyDataSetChanged();
scrollAdapter.setLoading();
scrollAdapter.setOnItemClickListener(this);
scrollAdapter.setOnLoadMoreListener(this);
}
Remove this line recycler.setAdapter(scrollAdapter); You need to set your adapter just once either in Activity's onCreate method or Fragment's onCreateView method.
In setAdapter() you dont need to do recycler.setAdapter(scrollAdapter); again, just do it at the beginning
I do something similar, but reversed, working as chat
messages.addAll(0, oldMessages);
mAdapter.notifyItemRangeInserted(0, oldMessages.size());
mAdapter.notifyItemChanged(oldMessages.size());
mAdapter.setLoaded();
Im adding the old messages of the char to the messages.
Then notifing the adapter I have updated the source
I uses the 0 to put at the beginning

Get unique item id from item list in Android

I was creating android project in that i am using itemlist view and pagination . while clicking on that particular item i want to get that item id.but i am not getting the unique id.
When i use position then each and every page it is getting form 0-9.
i have the field 'audit_id'. i want to assign this values as item id and i want to get . whether it is possible?
My Code is :
private class AsyncLogin extends AsyncTask<String, String, StringBuilder> {
ProgressDialog pdLoading = new ProgressDialog(Tblview.this);
HttpURLConnection conn;
URL url = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected StringBuilder doInBackground(String... params) {
try {
// Enter URL address where your php file resides
url = new URL("http://192.168.1.99/ashwad/ims/webservices/alldata.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "URL Exception", Toast.LENGTH_LONG).show();
e.printStackTrace();
return null;
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput method depict handling of both send and receive
conn.setDoInput(true);
conn.setDoOutput(true);
// Append parameters to URL
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("user_id", "sdfa")
.appendQueryParameter("password", "asffs");
String query = builder.build().getEncodedQuery();
// Open connection for sending data
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return null;
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
result = new StringBuilder();
String next1;
while ((next1 = bufferedReader.readLine()) != null) {
result.append(next1 + "\n");
}
Log.e("dfasf",result.toString());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
return result;
}
#Override
protected void onPostExecute(StringBuilder s) {
super.onPostExecute(s);
try {
JSONArray login;
JSONObject obj = new JSONObject(s.toString());
if(s.toString().contains("Result")) {
data = new ArrayList<String>();
login = obj.getJSONArray("Result");
for(int i=0;i<login.length();i++) {
JSONObject c = login.getJSONObject(i);
productsArray = c.getJSONArray(Latest_Products);
TOTAL_LIST_ITEMS=productsArray.length();
int val = TOTAL_LIST_ITEMS%NUM_ITEMS_PAGE;
val = val==0?0:1;
pageCount = (TOTAL_LIST_ITEMS/NUM_ITEMS_PAGE)+val;
for (int j = 0; j < productsArray.length(); j++) {
JSONObject cc = productsArray.getJSONObject(j);
//------------------------------------------------------------------------
Log.e("audit",cc.getString("phone_name"));
String audit_id_str = cc.getString("audit_id");
int audit_id =Integer.parseInt(audit_id_str);
listview.setSelection(audit_id);
data.add(cc.getString("phone_name") +"\n\n"+cc.getString("audit_status") );
loadList(0);
btn_next.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
increment++;
loadList(increment);
CheckEnable();
}
});
btn_prev.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
increment--;
loadList(increment);
CheckEnable();
}
});
//------------------------------------------------------------------------
}
}
pdLoading.dismiss();
//CheckEnable();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
private void loadList(int number)
{
ArrayList<String> sort = new ArrayList<String>();
title.setText("Page "+(number+1)+" of "+pageCount);
int start = number * NUM_ITEMS_PAGE;
for(int i=start;i<(start)+NUM_ITEMS_PAGE;i++)
{
if(i<data.size())
{
sort.add(data.get(i));
}
else
{
break;
}
}
sd = new ArrayAdapter<String>(Tblview.this,android.R.layout.simple_list_item_1,sort);
listview.setAdapter(sd);
}
private void CheckEnable()
{
if(increment+1 == pageCount)
{
btn_next.setEnabled(false);
btn_prev.setEnabled(true);
}
else if(increment == 0)
{
btn_prev.setEnabled(false);
btn_next.setEnabled(true);
}
else
{
btn_prev.setEnabled(true);
btn_next.setEnabled(true);
}
}
}
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int positon1 =position;
String a1 = Integer.toString(positon1);
Toast.makeText(getApplicationContext(),a1,Toast.LENGTH_SHORT).show();
}
});
If you are keeping count of page then you can add page number to item position.
That will give you unique number for each item.

Why is return registration successful?

require "findDoctorConnect.php";
$type = $_POST["type"];
$yourName = $_POST["YourName"];
$RegNum = $_POST["regNum"];
$FatherName = $_POST["fatherName"];
$Gender = $_POST["gender"];
$MobileNumber = $_POST["mobileNumber"];
$Password = $_POST["password"];
$sql_query = "select * from doctorregistration where MobileNumber='$MobileNumber';";
$result = mysqli_query($con, $sql_query);
if (mysqli_num_rows($result) > 0) {
$row = mysqli_fetch_assoc($result);
$temp = $row["MobileNumber"];
if ($temp == $MobileNumber) {
$row = mysqli_fetch_assoc($result);
echo "already found";
}
} else if (mysqli_query($con, $sql_query)) {
$sql_query = "insert into doctorregistration values('$type','$yourName','$RegNum','$FatherName','$Gender','$MobileNumber','$Password');";
$result = mysqli_query($con, $sql_query);
echo "successfull";
}
When I send data from my application to database, first time it's saved in database and it returns registration successfully, but when again with same data like my primary key is mobile number when I send data to database it again said me that registration successful but actually it does not save data this time. I want to return registration unsuccessful so what to do for that?
Here is my code:
public class BackgroundTask extends AsyncTask<String, Void, String> {
Context ctx;
AlertDialog alertDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
alertDialog=new AlertDialog.Builder(ctx).create();
}
public BackgroundTask(Context ctx) {
// TODO Auto-generated constructor stub
this.ctx=ctx;
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String reg_url="http://10.0.2.2/findDoctor/register.php";
String method=params[0];
if(method.equals("register")) {
String type=params[1];
String YourName=params[2];
String regNum=params[3];
String fatherName=params[4];
String gender=params[5];
String mobileNumber=params[6];
String password=params[7];
try {
URL url=new URL(reg_url);
HttpURLConnection connection=(HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
OutputStream OS=connection.getOutputStream();
BufferedWriter bufferedWriter=new BufferedWriter(new OutputStreamWriter(OS));
String Data=URLEncoder.encode("type","UTF-8")+"="+URLEncoder.encode(type,"UTF-8")+"&"+
URLEncoder.encode("YourName","UTF-8")+"="+URLEncoder.encode(YourName,"UTF-8")+"&"+
URLEncoder.encode("regNum","UTF-8")+"="+URLEncoder.encode(regNum,"UTF-8")+"&"+
URLEncoder.encode("fatherName","UTF-8")+"="+URLEncoder.encode(fatherName,"UTF-8")+"&"+
URLEncoder.encode("gender","UTF-8")+"="+URLEncoder.encode(gender,"UTF-8")+"&"+
URLEncoder.encode("mobileNumber","UTF-8")+"="+URLEncoder.encode(mobileNumber,"UTF-8")+"&"+
URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(Data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS=connection.getInputStream();
IS.close();
return "registration successful";
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
alertDialog.setMessage(result);
alertDialog.show();
if (result.endsWith("Registration seccussfull")) {
Toast.makeText(ctx, result,Toast.LENGTH_LONG).show();
} else if(result.endsWith("already found")){
alertDialog.setMessage("its works");
alertDialog.show();
}
}
}
enter image description here
Manage this condition on server side http://10.0.2.2/findDoctor/register.php and return some data to android code.
And in android read the data from server using InputStream and then check if registered success or not.
Edit : Add these lines and it will show proper output
InputStream IS=connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(IS));
String line;
StringBuilder builder = new StringBuilder();
while((line=reader.readLine()) != null)
builder.append(line);
IS.close();
return builder.toString();
These lines says that, you don't care about the server response.

d How can I use progress bar while fetching data from database?

I'm really bad at googling things I want so I decided to ask here. My question is is it possible to show a progress bar while fetching the data from the database? I'm using the typical code when fetching data(Pass value to php and the php will do the query and pass it again to android)
Edit(I have tried adding proggressdialog but the problem now is the loaded data will appear first before the progress dialog here's my AsyncTask code)
public class getClass extends AsyncTask<String, Void, String> {
public getClass()
{
pDialog = new ProgressDialog(getActivity());
}
URLConnection connection = null;
String command;
Context context;
String ip = new returnIP().getIpAddresss();
String link = "http://" + ip + "/android/getClass.php";//ip address/localhost
public URLConnection getConnection(String link) {
URL url = null;
try//retrieves link from string
{
url = new URL(link);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try//opens the url link provided from the "link" variable
{
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connection.setDoOutput(true);
return connection;
}
public String getResult(URLConnection connection, String logs) {
//this is the functions that retrieves what the php file echoes
//everything that php throws, the phone receives
String result = "";
OutputStreamWriter wr = null;
try {
wr = new OutputStreamWriter(connection.getOutputStream());//compiles data to be sent to the receiver
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.write(logs);
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.flush();//clears the cache-esque thingy of the writer
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String line = null;
//Read server response
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
result = sb.toString();
return result;
}
#Override
protected void onPreExecute() {
pDialog.setMessage("Loading...");
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String result = "";
//Toast.makeText(View_Classes.this, "ako n una", Toast.LENGTH_LONG).show();
try {
//first data sent is sent in command
command = (String) arg0[0];//it's in array, because everything you input here is placed in arrays
//Toast.makeText(View_Classes.this, "andtio n me", Toast.LENGTH_LONG).show();
if (command == "getCourses") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
result = getResult(connection, logs);
} else if (command == "getSections") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
logs += "&course=" + URLEncoder.encode(course, "UTF-8");
result = getResult(connection, logs);
}
return result;
} catch (Exception e) {
return result;
}
}
#Override
protected void onPostExecute(String result) {//this is going to be the next function to be done after the doInBackground function
// TODO Auto-generated method stub
if (pDialog.isShowing()) {
pDialog.dismiss();
}
if (result.equalsIgnoreCase(""))//if there's nothing to return, the text "No records" are going to be thrown
{
} else //Array adapter is needed, to be a place holder of values before passing to spinner
{
}
}
}
Have you tried using an AsyncTask?
You can show your progress bar on the preExecute method and then hide it on postExecute. You can do your querying inside the doInBackground method.
In addition to what #torque203 pointed, I would suggest you to check
http://developer.android.com/reference/android/os/AsyncTask.html#onProgressUpdate(Progress...)
this method was created for that purpose, showing progress to the user.
From developers docs:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
#Override
protected void onPreExecute() {
//show progress bar here
}
protected Long doInBackground(URL... urls) {
//Pass value to PHP here
//get values from your PHP
}
protected void onPostExecute(Long result) {
//Here you are ready with your PHP value. Dismiss progress bar here.
}
}
public void onPreExecute() {
Progress Dialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
}
public void doInBackground() {
//do your JSON Coding
}
public void onPostExecute() {
Progress Dialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
}
public URLConnection getConnection(String link) {
URL url = null;
try//retrieves link from string
{
url = new URL(link);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try//opens the url link provided from the "link" variable
{
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connection.setDoOutput(true);
return connection;
}
public String getResult(URLConnection connection, String logs) {
//this is the functions that retrieves what the php file echoes
//everything that php throws, the phone receives
String result = "";
OutputStreamWriter wr = null;
try {
wr = new OutputStreamWriter(connection.getOutputStream());//compiles data to be sent to the receiver
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.write(logs);
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.flush();//clears the cache-esque thingy of the writer
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String line = null;
//Read server response
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
result = sb.toString();
return result;
}
public class getClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
pDialog.setMessage("Loading...");
pDialog.show();
URLConnection connection = null;
String command;
Context context;
String ip = new returnIP().getIpAddresss();
String link = "http://" + ip + "/android/getClass.php";//ip address/localhost
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String result = "";
//Toast.makeText(View_Classes.this, "ako n una", Toast.LENGTH_LONG).show();
try {
//first data sent is sent in command
command = (String) arg0[0];//it's in array, because everything you input here is placed in arrays
//Toast.makeText(View_Classes.this, "andtio n me", Toast.LENGTH_LONG).show();
if (command == "getCourses") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
result = getResult(connection, logs);
} else if (command == "getSections") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
logs += "&course=" + URLEncoder.encode(course, "UTF-8");
result = getResult(connection, logs);
}
return result;
} catch (Exception e) {
return result;
}
}
#Override
protected void onPostExecute(String result) {//this is going to be the next function to be done after the doInBackground function
// TODO Auto-generated method stub
if (pDialog.isShowing()) {
pDialog.dismiss();
}
if (result.equalsIgnoreCase(""))//if there's nothing to return, the text "No records" are going to be thrown
{
} else //Array adapter is needed, to be a place holder of values before passing to spinner
{
}
}
}

Categories

Resources