Cursor implement on PreparedStatement in AsyncTask - java

So I am trying to implement a Cursor to my class so i can populate my datagrid (not sure if that is the right way to do it when i need to use callable for SP and prepared statement) which i made from this guide here but i gets a
DataGridActivity.Itemnumber is not abstract and does not override abstract method respond(Bundle) in Cursor
i am not sure how to implement the abstract method here as i
normaly use getstring methode for my prepared statements wonder if there is somehow i could do that instead to populate my grid instead of using the Cursor
public class Itemnumber extends AsyncTask<String,String,String> implements Cursor {
String z = "";
#Override
protected void onPreExecute() {
}
#Override
protected void onPostExecute(String r) {
}
#Override
protected String doInBackground(String... params) {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
PreparedStatement preparedStatement = null;
String sqli = "select ID,ItemNumber,Trashed,Sold from [file].[Item] where [ItemNumber] =?";
preparedStatement = con.prepareStatement(sqli);
preparedStatement.setString(1, "test");
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
} else {
}
}
} catch (Exception ex) {
z = "Exceptions";
}
return z;
}
#Override
public Bundle respond(Bundle extras){
moveToFirst();
return Bundle.EMPTY;
}
}
My Datagrid activity class
Cursor csr = new Itemnumber();
//create DataTable object
DataTable dtDataSource = new DataTable();
//define column
dtDataSource.addAllColumns(new String[]{"column_1", "column_2","column_3", "column_4});
//create DataRow
DataTable.DataRow drRow;
//populate data from cursor into DataSource
if(csr.moveToFirst()){
do{
drRow = dtDataSource.newRow();
drRow.set("column_1", csr.getString(csr.getColumnIndex("field_1")));
drRow.set("column_2", csr.getString(csr.getColumnIndex("field_2")));
drRow.set("column_2", csr.getString(csr.getColumnIndex("field_3")));
drRow.set("column_4", csr.getString(csr.getColumnIndex("field_4")));
dtDataSource.add(drRow);
} while(csr.moveToNext());
csr.close();
}
/**
* Prepare the DataGrid
*/
//initialize DataGrid
DataGrid dg = (DataGrid)findViewById(R.id.datagrid);
//define column style, bond each DataGrid column by DataTable column
dg.addColumnStyles(new DataGrid.ColumnStyle[]{
new DataGrid.ColumnStyle(getString(R.string.ID), "column_1", 80),
new DataGrid.ColumnStyle(getString(R.string.ItemNumber), "column_2", 120),
new DataGrid.ColumnStyle(getString(R.string.Trashed), "column_3", 100),
new DataGrid.ColumnStyle(getString(R.string.Sold), "column_4", 150)
});
//set the DataTable as source
dg.setDataSource(dtDataSource);
//generate the DataGrid
dg.refresh();

You must override last method in Itemnumber class.
This method is in interface Cursor, and named: respond(Bundle)
So, if Your class Itemnumber implemented Cursor, please add
#Override
Bundle respond(Bundle extras){
return Bundle.EMPTY;
}
and implemented, what Your method must return

I figured out how to do it with just use my prepaered statement.
As implementing all the abstract methodes and interfaces didn't seemed to be anything near logical
public class DataGridActivity extends Activity {
/** Called when the activity is first created. */
ConnectionClass connectionClass;
//define column
DataTable.DataRow drRow;
DataTable dtDataSource = new DataTable();
Button btnsearch;
DataGrid dg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.datagridt);
dg = (DataGrid)findViewById(R.id.datagrid);
btnsearch = (Button) findViewById(R.id.btnsearch);
connectionClass = new ConnectionClass(this.getApplicationContext());
/**
* Prepare the DataGrid
*/
//initialize DataGrid
//define column style, bond each DataGrid column by DataTable column
dg.addColumnStyles(new DataGrid.ColumnStyle[]{
new DataGrid.ColumnStyle(getString(R.string.dito_nr), "column_1", 80),
new DataGrid.ColumnStyle(getString(R.string.Biltype), "column_2", 120),
new DataGrid.ColumnStyle(getString(R.string.kort_nr), "column_3", 100),
new DataGrid.ColumnStyle(getString(R.string.Del_Type), "column_4", 150)
});
}
public class Itemnumber extends AsyncTask<String,String,String> {
String z = "";
#Override
protected void onPreExecute() {
dtDataSource.addAllColumns(new String[]{"column_1", "column_2","column_3", "column_4"});
drRow = dtDataSource.newRow();
dtDataSource.add(drRow);
dg.setDataSource(dtDataSource);
dg.refresh();
}
#Override
protected void onPostExecute(String r) {
}
#Override
protected String doInBackground(String... params) {
try {
Connection con = connectionClass.CONN();
if (con == null) {
z = "Error in connection with SQL server";
} else {
PreparedStatement preparedStatement = null;
String sqli = "select ID,ItemNumber,Trashed,Sold from [file].[Item]";
preparedStatement = con.prepareStatement(sqli);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
//create DataRow
drRow.set("column_1", rs.getString(1));
drRow.set("column_2", rs.getString(2));
drRow.set("column_3", rs.getString(3));
drRow.set("column_4", rs.getString(4));
} else {
}
}
} catch (Exception ex) {
z = "Exceptions";
}
return z;
}
}
public void btnsearch (View view) {
// TODO Auto-generated method stub
Itemnumber item = new Itemnumber();
item.execute("");
}
}

Related

Populate listview with multiple columns from ms sql procedure

in my project it is necessary to implement loading data from ms sql procedure into listview. I created my listview layout, configured the adapter according to this example - https://github.com/codepath/android_guides/wiki/Using-an-ArrayAdapter-with-ListView.
But I ran into a problem - no new lines are created in my listview, but the first one is overwritten.
Here is my code:
Method to call sql procedure and populate listview
public void fillVagonList ()
{
ResultSet rs = null;
PreparedStatement ps = null;
try {
ConnectToSql connectToSql = new ConnectToSql();
SqlConnect = connectToSql.connect();
if (SqlConnect != null)
{
String SPsql = "EXEC mobile3_GETCARLIST ?,?,?,?";
ps = SqlConnect.prepareStatement(SPsql);
ps.setEscapeProcessing(true);
ps.setQueryTimeout(1000);
ps.setInt(1, LoginActivity.SesId);
ps.setString(2, EquipmentWagon.deadend);
ps.setString(3, EquipmentWagon.sectorName);
ps.setInt(4, EquipmentWagon.operID);
rs = ps.executeQuery();
vagonNumberList = new ArrayList<String>();
vagonNatList = new ArrayList<String>();
vagonLengthList = new ArrayList<String>();
//completeList = new ArrayList<String>();
while (rs.next())
{
Vagon vagon = new Vagon(rs.getString(2),rs.getString(1),rs.getString(5));
ArrayList<Vagon> vagonArrayList = new ArrayList<Vagon>();
VagonAdapter adapter = new VagonAdapter(getContext(),vagonArrayList);
lvVagonList.setAdapter(adapter);
adapter.addAll(vagon);
}
} else {
ConnectionResult = "Check Connection";
}
} catch (SQLException se)
{
System.out.println("Error al ejecutar SQL" + se.getMessage());
se.printStackTrace();
throw new IllegalArgumentException("Error al ejecutar SQL: " + se.getMessage());
} finally
{
try
{
rs.close();
ps.close();
SqlConnect.close();
}
catch (SQLException ex)
{
ex.printStackTrace();
}
}
}
Vagon class:
public class Vagon {
public String carNumber;
public String natList;
public String vagonLength;
public Vagon(String carNumber, String natList,String vagonLength)
{
this.carNumber = carNumber;
this.natList = natList;
this.vagonLength = vagonLength;
}
}
VagonAdapter class:
public class VagonAdapter extends ArrayAdapter<Vagon> {
public VagonAdapter(Context context, ArrayList<Vagon> vagons) {
super(context, 0, vagons);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Vagon vagon = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.adapter_vagon_view, parent, false);
}
// Lookup view for data population
TextView tvNomVag = (TextView) convertView.findViewById(R.id.tvNomVag);
TextView tvNatList = (TextView) convertView.findViewById(R.id.tvNatList);
TextView tvCarLength = (TextView) convertView.findViewById(R.id.tvCarLength);
// Populate the data into the template view using the data object
tvNomVag.setText(vagon.carNumber);
tvNatList.setText(vagon.natList);
tvCarLength.setText(vagon.vagonLength);
// Return the completed view to render on screen
return convertView;
}
}
What do I need to do so that the first line is not overwritten, but a new one is added? Help me out, i'm stucked on this moment. Thanks.
i modified this part in method :
ArrayList<Vagon> vagonArrayList = new ArrayList<>();
for (int i = 0; i < vagonNumberList.size(); i++) {
try {
vagonArrayList.add(new Vagon(vagonNumberList.get(i),vagonNatList.get(i),vagonLengthList.get(i)));
} catch (Exception e) {
e.printStackTrace();
}
}
VagonAdapter adapter = new VagonAdapter(getContext(),vagonArrayList);
lvVagonList.setAdapter(adapter);

Get data from a table in sql to a textview in android studio from a specific row

I have a table in ms sql this table contains FName and FInfo i want to get th FInfo according to the FName like if the FName in the app is equal to john it gets the FInfo of john in the same row.
i have tried everything including query's and Result set but it didn't work out for me.
here is my code:
public class InsideFamily extends AppCompatActivity {
private TextView inf;
private boolean success = false; // boolean
private ConnectionClass connectionClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inside_family);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
inf = (TextView) findViewById(R.id.thefamilyinf);
connectionClass = new ConnectionClass();
SyncData orderData = new SyncData();
orderData.execute("");
}
private class SyncData extends AsyncTask<String, String, String> {
String msg = "No Data Found";
ProgressDialog progress;
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(InsideFamily.this, "Synchronising",
"Please Wait...", true);
}
#Override
protected String doInBackground(String... strings)
{
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
Connection conn = connectionClass.CONN();
if (conn == null) {
msg = "Please Check Your Connection";
success = false;
} else {
String gettingfam = getIntent().getStringExtra("defamily");
String query = "SELECT * FROM family where FName='" + gettingfam + "'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) {
while (rs.next()) {
try {
inf.setText((rs.getString("FInfo")));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
success = false;
}
}
});
return msg;
}
#Override
protected void onPostExecute(String
msg)
{
progress.dismiss();
Toast.makeText(InsideFamily.this, msg + "", Toast.LENGTH_LONG).show();
if (success == false) {
} else {
try {
} catch (Exception ex) {
}
}
}
}
}
the errors i get is that it brings a toast for me saying that "No Data Found!"
which means that that the result set equals null how can i fix it??
I found the answer
the wrong was in the query
because its nvarchar i have to wright
"SELECT * FROM family WHERE FName = (N'" +dta+ "')"
rather than
"SELECT * FROM family where FName='" + gettingfam + "'"

java.lang.ClassCastException: com.github.mikephil.charting.data.Entry cannot be cast to com.github.mikephil.charting.data.PieEntry

Accepting data from database and displaying it on Table Layout and using that data creating a piechart with MpAndroidChart Library but getting the error as stated above
I am transfering arraylist from one activity to other using putextra and getSerializableExtra while accepting "the error is shown as above"
I am sharing my code please help
yValue is my arraylist where data is stored
transfering it to mylist using intent but this is generating error
My code:-
public class DisplayDate extends MainActivity{
public ArrayList<PieEntry> yValues = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_date);
doInBackground();
pieChart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent pieIntent = new Intent(DisplayDate.this,DisplayPiechart.class);
pieIntent.putExtra("Pie Values",yValues);
startActivity(pieIntent);
}
});
}
public void doInBackground()
{
ConnectionHelper connectString = new ConnectionHelper();
connect = connectString.connectionClass();
Log.w("Android","Connecting....");
if (connect == null)
{
Log.w("Android","Connection Failed");
ConnectionResult = "Check Your Internet Connection";
}
else
{
Log.w("Android","Connected");
String query = "Select No_,Name,Date,[Net Amount],[Gross Amount] from [CRONUS LS 1010 W1 Demo$Store] as str,[CRONUS LS 1010 W1 Demo$Transaction Header] as trans where str.[No_] = trans.[Store No_] and trans.[Date] between '"+Actual_Start+"' and '"+Actual_End+"' ";
try
{
Statement stmt = connect.createStatement();
ResultSet rs = stmt.executeQuery(query);
Log.w("Android","database Connected");
while (rs.next()) {
TR = new TableRow(this);
TV1.setText(rs.getString("No_"));
TV2.setText(rs.getString("Name"));
TV4.setText(rs.getString("Date"));
TV5.setText(rs.getString("Net Amount"));
TV3.setText(rs.getString("Gross Amount"));
TL.addView(TR);
c = TV3.getText().toString();
a = Float.parseFloat(c);
d = TV1.getText().toString();
yValues.add(new PieEntry(a,d));
}
ConnectionResult = "Successful";
isSuccess = true;
connect.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
}
}
class DisplayPiechart extends DisplayDate{
com.github.mikephil.charting.charts.PieChart pieChart;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_piechart);
Intent i = getIntent();
ArrayList<PieEntry> myList = (ArrayList<PieEntry>) i.getSerializableExtra("Pie Values");
//Error at below line
PieDataSet dataSet = new PieDataSet(myList, "Stores");
dataSet.setSliceSpace(2f);
dataSet.setSelectionShift(6f);
dataSet.setColors(ColorTemplate.MATERIAL_COLORS);
PieData data = new PieData(dataSet);
data.setValueTextSize(10f);
data.setValueTextColor(Color.BLACK);
pieChart.setData(data);
}
}
This is a very old question but was running into the same issue. I'm new at this so take it with a grain of salt. There is probably a better way of solving it but posting it in case it helps someone.
I solved it by creating an ArrayList in the receiving activity as such:
ArrayList<Entry> receivedData;
receivedData = new ArrayList<>();
Then stored the data passed from the first activity into this ArrayList:
receivedData = getIntent().getParcelableArrayListExtra("data");
// Get size of ArrayList
int size = receivedData.size();
// Getting individual X and Y values from each ArrayList element
for(int k = 0; k < size; k++){
// Adding X and Y values as entries in a different
// ArrayList barEntriesArrayList
addDataPointsToGraph((int) receivedData.get(k).getX(), receivedData.get(k).getY());
}
And here is that Method:
private void addDataPointsToGraph(int x, float y){
barEntriesArrayList.add(new BarEntry(x, y));
}
I then supplied this ArrayList barEntriesArrayList to the dataSet
// creating a new bar data set.
barDataSet2 = new BarDataSet(barEntriesArrayList, getResources().getString(R.string.valuePerDay));
I was using these two tutorials as a guide when generating my graph
https://www.geeksforgeeks.org/how-to-create-a-barchart-in-android/
https://learntodroid.com/how-to-display-a-bar-chart-in-your-android-app/

Spinner data in Main Activity is lost after using camera for scanning a QR Code

Hi I am new to Android programming.
When the mainacitivity is loaded I can fetch the data from sql server and populate it in spinner. I can choose an item from spinner and scan the qrcode/ barcode. Once i stop the camera and return to the MainActivity, I can't find any data in the spinner. Please let me know if you need more info about the question. I have provided the whole code in MainActivity.java file.
package com.example.vxt.barcodescanner;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.Button;//import android.widget.ProgressBar;import android.widget.Spinner;import android.app.AlertDialog;import android.content.DialogInterface;import com.google.zxing.Result;import me.dm7.barcodescanner.zxing.ZXingScannerView;import java.sql.Connection;import java.sql.ResultSet;import java.sql.PreparedStatement;import java.util.ArrayList;import static com.example.vxt.barcodescanner.R.id.spinner;
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler{
ConnectionClass connectionClass;
//ProgressBar pbbar;
Spinner spinnerProducts;
private ZXingScannerView mScannerView;
ArrayList<String> scanned_data = new ArrayList<String>();
ArrayList<String> data = new ArrayList<String>();
String productSelected;
Button scan, pushToDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
connectionClass = new ConnectionClass();
//pbbar = (ProgressBar) findViewById(R.id.pbbar);
//pbbar.setVisibility(View.VISIBLE);
spinnerProducts = (Spinner) findViewById(spinner);
scan = (Button) findViewById(R.id.button);
pushToDB = (Button) findViewById(R.id.button3);
try {
Connection con = connectionClass.CONN();
if (con != null) {
String query = "select * from Products";
PreparedStatement preparedStatement = con.prepareStatement(query);
ResultSet rs = preparedStatement.executeQuery();
data.add("<--- Select a Product --->");
while(rs.next()){
String product = rs.getString("Product");
String id = Integer.toString(rs.getInt("Id"));
data.add(product + "----" + id);
}
ArrayAdapter NoCoreAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, data);
spinnerProducts.setAdapter(NoCoreAdapter);
//pbbar.setVisibility(View.GONE);
scan.setEnabled(false);
pushToDB.setEnabled(false);
}
} catch (Exception ex) {
//pbbar.setVisibility(View.GONE);
ex.printStackTrace();
}
spinnerProducts.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(spinnerProducts.getSelectedItemPosition() != 0){
scan.setEnabled(true);
}
productSelected = spinnerProducts.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState) { /* do nothing */ }
public void onClick(View v){
mScannerView = new ZXingScannerView(MainActivity.this);
setContentView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
public void onClickDB(View v){
//pbbar.setVisibility(View.VISIBLE);
pushToDB.setEnabled(false);
try {
Connection con = connectionClass.CONN();
if (con != null) {
String query, query1;
PreparedStatement preparedStatement, preparedStatement1; // = con.prepareStatement(query);
ResultSet rs; // = preparedStatement.executeQuery();
String[] splArray;
//SimpleCursorAdapter adapter = (SimpleCursorAdapter) spinnerProducts.getAdapter();
for (int position = 1; position < scanned_data.size(); position++) {
splArray = scanned_data.get(position).split(",");
query = "select * from Products_Barcode where ProductId ='" + splArray[1] + "'";
preparedStatement = con.prepareStatement(query);
rs = preparedStatement.executeQuery();
if(rs.next()){
query1 = "Update Products_Barcode set Barcode = '" + splArray[2] + "' where ProductId = '" + splArray[1] + "'";
preparedStatement1 = con.prepareStatement(query1);
preparedStatement1.executeQuery();
}
else{
query1 = "insert into Products_Barcode values ('" + splArray[1] + "','" + splArray[0] + "','" + splArray[2] + "');";
preparedStatement1 = con.prepareStatement(query1);
preparedStatement1.executeQuery();
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Data tranferred successfully")
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
} catch (Exception ex) {
//pbbar.setVisibility(View.GONE);
ex.printStackTrace();
}
}
#Override
protected void onPause(){
super.onPause();
mScannerView.stopCamera();
}
#Override
public void handleResult(Result result) {
//if(chk == 0){
Log.v("handleResult", result.getText());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
String source_text = result.getText();
String prod = productSelected.replace("----", ",");
scanned_data.add(prod + "," + source_text);
builder.setTitle("Scan Result");
builder.setMessage("Scan complete")
//chk = 1;
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
dialog.cancel();
/*chk = 1;
mScannerView.resumeCameraPreview(MainActivity.this);*/
}
});
spinnerProducts.setSelection(0);
scan.setEnabled(false);
if(!pushToDB.isEnabled()){
pushToDB.setEnabled(true);
}
mScannerView.stopCamera();
setContentView(R.layout.activity_main);
//pbbar.setVisibility(View.GONE);
ArrayAdapter NoCoreAdapter = new ArrayAdapter(MainActivity.this,android.R.layout.simple_spinner_item, data);
NoCoreAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerProducts.setAdapter(NoCoreAdapter);
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
You need to save the spinner data somewhere inside the onPause method.
#Override
protected void onPause(){
Data data = spinner.getData(); //Implement your own logic
}
When You come back to the MainActivity your onResume method is called where you have to feed the data back to the spinner.
#Override
protected void onResume(){
spinner.setData(data); //Implement your own logic
}
[EDIT]
The problem is, you are using the setContentView() multiple times which is a bad practice. According to Android documentation
Set the activity content to an explicit view. This view is placed directly into the activity's view hierarchy.
If you want to achieve what you currently wish, you should use fragments.
In short, do not call the setContentView() multiple times. Use fragment to show multiple xml without changing the activity.

AsyncTask wont change the values of other variables

i am making an android app that uses jdbc to connect to a database, jdbc needs AsyncTask, i read a tutorial about it but, i have all kinds of troubles !
code :
// login stuff
Button Login;
EditText Username, Password;
String db_username, db_password;
// database variables
Database d;
ResultSet rs;
Statement stmt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
getActionBar().hide();
// defining stuff
Login = (Button) findViewById(R.id.login);
Username = (EditText) findViewById(R.id.username);
Password = (EditText) findViewById(R.id.password);
db_password = "-1";
// focus on the enter username
Username.requestFocus();
Login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// checking for the password and stuff
Con deploy = new Con();
deploy.execute();
// waiting until data is back
while (db_password.equals("-1")){
}
// checking the entered password
if (db_password.equals(Password.getText())) {
Intent i = new Intent(Login.this, Manager.class);
i.putExtra("name", db_username);
startActivity(i);
finish();
}
}
});
}
// connection class
private class Con extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
d = new Database();
d.connect();
try {
// putting the username and pass in the result set
stmt = d.createStatement();
rs = stmt
.executeQuery("SELECT username,password from users WHERE username='"
+ Username.getText() + "'");
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(Void result) {
try {
if (rs.next()) {
db_username = rs.getString("username");
db_password = rs.getString("password");
System.out.println("check point");
System.out.println(db_password);
db_password = "0";
} else {
Username.setText("");
Password.setText("");
db_password = "0";
}
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
super.onPostExecute(result);
}
}
after testing i figured, inside the thread the value changes as in the database, but on the main thread the two variables db_username db_password never changes !
i made these variables static but didnt work , please help
Solved : i used this instead of AcyncTask and solved everything:
new Thread(new Runnable() {
public void run() {
}).start();
private class Con extends AsyncTask<Void, Void, ResultSet > {
#Override
protected ResultSet doInBackground(Void... params) {
d = new Database();
d.connect();
ResultSet rs;
try {
// putting the username and pass in the result set
Statement stmt = d.createStatement();
rs = stmt
.executeQuery("SELECT username,password from users WHERE username='"
+ Username.getText() + "'");
} catch (Exception e) {
return new ResultSet(); // depends on what you want to do on error
}
return rs;
}
#Override
protected void onPostExecute(ResultSet result) {
super.onPostExecute(result);
try {
if (result.next()) {
db_username = result.getString("username");
db_password = result.getString("password");
System.out.println("check point");
System.out.println(db_password);
// db_password = "0"; this always makes it zero at the end of the day
} else {
Username.setText("");
Password.setText("");
db_password = "0";
}
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
Edit also change this if (db_password.equals(Password.getText().toString())) { its in your onclick listener
use this asnyc ayt.. check closing tags and stuff..

Categories

Resources