Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example.mysqlexampleproject;
- import androidx.appcompat.app.AppCompatActivity;
- import android.content.Context;
- import android.content.Intent;
- import android.content.res.Resources;
- import android.os.AsyncTask;
- import android.os.Bundle;
- import android.view.View;
- import android.widget.Adapter;
- import android.widget.ArrayAdapter;
- import android.widget.Button;
- import android.widget.ListView;
- import android.widget.TextView;
- import org.json.JSONArray;
- import java.sql.Array;
- import java.sql.Connection;
- import java.sql.DriverManager;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- import java.sql.Statement;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.LinkedHashMap;
- import java.util.Map;
- public class MainActivity extends AppCompatActivity {
- //googleBtn.setOnClickListener(new View.OnClickListener() {
- //
- // @Override
- // public void onClick(View v) {
- // //String google = "https://www.google.com";
- // //Uri webaddress = Uri.parse(google);
- //Intent gotoGoogle = new Intent(Intent.ACTION_VIEW, webaddress);
- //if (gotoGoogle.resolveActivity(getPackageManager()) != null) {
- // startActivity(gotoGoogle);
- //}
- // }
- // });
- //}
- ArrayAdapter ArrayAdapter;
- // Construct the data source
- ArrayList<user> arrayOfUsers = new ArrayList<user>();
- // Create the adapter to convert the array to views
- UsersAdapter adapter = new UsersAdapter(this, arrayOfUsers);
- // Attach the adapter to a ListView
- ListView listView = (ListView) findViewById(R.id.myListView);
- //listView.setAdapter(ArrayAdapter);
- Context thisContext;
- ListView myListView;
- TextView progressTextView;
- Integer resource;
- //Map<Integer, String> usersMap = new LinkedHashMap<Integer, String>(); //A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value.
- //String[][] userList;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- //Attempts to launch an activity within our own app
- //Button secondActivityBtn = (Button)findViewById(R.id.loginBtn);
- //secondActivityBtn.setOnClickListener(new View.OnClickListener() {
- // @Override
- // public void onClick(View v_) {
- // Intent startIntent = new Intent(getApplicationContext(), loginScreen.class);
- // //show how to pass info to another activity
- // startIntent.putExtra("com.example.mysqlexampleproject.NAME", "TEST");
- // startActivity(startIntent);
- // }
- //});
- //Attempt to launch an activity outside our app
- //Button googleBtn = (Button)findViewById(R.id.signUpBtn);
- Resources res = getResources();
- myListView = (ListView) findViewById(R.id.myListView);
- progressTextView = (TextView) findViewById(R.id.progressTextView);
- thisContext = this;
- listView.setAdapter(adapter);
- progressTextView.setText("");
- Button btn = (Button) findViewById(R.id.getDataButton);
- btn.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View v) {
- GetData retrieveData = new GetData();
- retrieveData.execute("");
- }
- });
- }
- private class GetData extends AsyncTask<String,String,String> {
- Integer flag = 0;
- //Integer user = 0;
- 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://" + 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 {
- flag = 1;
- Class.forName(JDBC_DRIVER);
- conn = DriverManager.getConnection(DB_URL, DBStrings.USERNAME, DBStrings.PASSWORD);
- //conn = DriverManager.getConnection(DB_URL);
- flag = 2;
- stmt = conn.createStatement();
- String sql = "SELECT * FROM users";
- ResultSet rs = stmt.executeQuery(sql);
- //lets hope this works
- ArrayList<user> users = new ArrayList<>();
- /*
- // Add item to adapter
- User newUser = new User("Nathan", "San Diego");
- adapter.add(newUser);
- // Or even append an entire new collection
- // Fetching some data, data has now returned
- // If data was JSON, convert to ArrayList of User objects.
- JSONArray jsonArray = ...;
- ArrayList<User> newUsers = User.fromJson(jsonArray)
- adapter.addAll(newUsers);
- */
- flag = 3;
- while (rs.next()) {
- Integer userID = rs.getInt("userID");
- String firstName = rs.getString("firstName");
- String surname = rs.getString("surname");
- String username = rs.getString("username");
- user newUser = new user(username, userID);
- newUser.user_id = userID;
- newUser.username = username;
- //UsersAdapter.add(newUser);
- adapter.add(newUser);
- //Double price = rs.getDouble("price");
- //userList[user][0] = firstName;
- //userList[user][1] = surname;
- //userList[user][2] = username;
- //usersMap.put(userID, firstName);
- //usersMap.put(name, price);
- //user += 1;
- flag = 4;
- }
- msg = "Process complete.";
- rs.close();
- stmt.close();
- conn.close();
- //milbs recommends you create static array list of users in user class (or new class)
- //ArrayList<user> users = new ArrayList<>();
- //user newUser = new user();
- //newUser.user_id = 5;
- //newUser.username = "TJM4";
- //users.add(newUser);
- //users.contains(newUser);
- //milbs recommends you dont use these
- //HashMap<String, user> newHashmap = new HashMap<>();
- //newHashmap.put("new user string", newUser);
- //user userfromhashmap = newHashmap.get("new user string");
- } catch (SQLException connError) {
- msg = "An exception was thrown for JDBC.\nFlag: " + flag.toString();
- 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 (userList.length() > 0) {
- // itemAdapter = new ItemAdapter(thisContext, userList);
- //myListView.setAdapter(itemAdapter);
- //}
- //if (usersMap.size() > 0) {
- if (arrayOfUsers.size() > 0) {
- //itemAdapter = new ItemAdapter(thisContext, usersMap);
- ArrayAdapter = new ArrayAdapter(thisContext, resource);
- myListView.setAdapter(ArrayAdapter);
- }
- }
- }
- } //END OF MAINACTIVITY
- //////ERROR//////
- E/AndroidRuntime: FATAL EXCEPTION: main
- Process: com.example.mysqlexampleproject, PID: 7036
- java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.mysqlexampleproject/com.example.mysqlexampleproject.MainActivity}: java.lang.IllegalStateException: System services not available to Activities before onCreate()
- at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2679)
- at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
- at android.app.ActivityThread.-wrap11(Unknown Source:0)
- at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
- at android.os.Handler.dispatchMessage(Handler.java:106)
- at android.os.Looper.loop(Looper.java:164)
- at android.app.ActivityThread.main(ActivityThread.java:6494)
- at java.lang.reflect.Method.invoke(Native Method)
- at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
- at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
- Caused by: java.lang.IllegalStateException: System services not available to Activities before onCreate()
- at android.app.Activity.getSystemService(Activity.java:5915)
- at android.view.LayoutInflater.from(LayoutInflater.java:229)
- at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:210)
- at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:204)
- at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:190)
- at com.example.mysqlexampleproject.UsersAdapter.<init>(UsersAdapter.java:18)
- at com.example.mysqlexampleproject.MainActivity.<init>(MainActivity.java:52)
- at java.lang.Class.newInstance(Native Method)
- at android.app.Instrumentation.newActivity(Instrumentation.java:1174)
- at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2669)
- at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
- at android.app.ActivityThread.-wrap11(Unknown Source:0)
- at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
- at android.os.Handler.dispatchMessage(Handler.java:106)
- at android.os.Looper.loop(Looper.java:164)
- at android.app.ActivityThread.main(ActivityThread.java:6494)
- at java.lang.reflect.Method.invoke(Native Method)
- at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
- at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
- Process 7036 terminated.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement