I'm working on this homework assignment and trying to connect to a local MySQL database, the app installs and runs in my AVD but when I click the 'get data' button, i'm returned the connError message.
I'm very new at this and want to get into this field, so i've looked up multiple videos and articles, but for some reason I am unable to find a solution to this issue. Here is my main java code.
public class MainActivity extends AppCompatActivity {
ItemAdapter itemAdapter;
Context thisContext;
ListView myListView;
TextView progressTextView;
Map<String, Double> fruitsMap = new LinkedHashMap<String, Double>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resources res = getResources();
myListView = findViewById(R.id.myListView);
progressTextView = findViewById(R.id.progressTextView);
thisContext = this;
progressTextView.setText("");
Button btn = findViewById(R.id.getDataBtn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
GetData retrieveData = new GetData();
retrieveData.execute("");
}
});
}
private class GetData extends AsyncTask<String, String, String> {
String msg = "";
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
// Example: 10.20.30.40.3306
static final String DB_URL = "jdbc:mysql://localhost:3306/fruits" +
DbStrings.DATABASE_URL + "/" +
DbStrings.DATABASE_NAME;
@Override
protected void onPreExecute() {
progressTextView.setText("Connecting to database...");
}
@Override
protected String doInBackground(String... params) {
Connection conn = null;
Statement stmt = null;
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection
(DB_URL, DbStrings.USERNAME, DbStrings.PASSWORD);
stmt = conn.createStatement();
String sql = "SELECT * FROM fruits";
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
String name = rs.getString("item");
double price = rs.getDouble("price");
fruitsMap.put(name, price);
}
msg = "Process complete";
rs.close();
stmt.close();
conn.close();
} catch (SQLException connError) {
msg = "An exception was thrown for JDBC.";
connError.printStackTrace();
} catch (ClassNotFoundException e) {
msg = "A class not found exception was thrown.";
e.printStackTrace();
} finally {
try {
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String msg) {
progressTextView.setText(this.msg);
if (fruitsMap.size() > 0) {
itemAdapter = new ItemAdapter(thisContext, fruitsMap);
myListView.setAdapter(itemAdapter);
}
}
}
} //End of MainActivity
The expected results should be a database showing of various fruits and their prices in a TextView.