How to loop TreeNode of P:treetable data - primefaces

I want to Loop TreeTable object in Java code. Here is by Tree Creation code
public TreeNode getTreeData()
{
lstTestProcessByRelease = testProcessBo.findAllTestProcessByReleaseGroupBy(getTestSuite(), getReleaseByTabName());
List<TestProcess> lstTestScenario = new ArrayList<TestProcess>();
int parentCount=0;
root1 = new DefaultTreeNode(new TestProcess("TestScenario","TestCase",0,0),null);
for(TestProcess tp : lstTestProcessByRelease)
{
parentCount = parentCount + 1;
ExecutionParentOrderValue.put(parentCount, parentCount);
TreeNode parent = new DefaultTreeNode(new TestProcess(tp.getTestScenarioName(), tp.getTestScenarioName(), 0, parentCount),root1);
System.out.println("============"+ tp.getTestScenarioName() +"=================");
System.out.println("Scenario Name (ROWKEY) :"+ parent.getRowKey());
lstTestScenario = testProcessBo.findAllTestCasesByTestScenarioName(tp.getTestSuite(), tp.getReleaseName(), tp.getTestScenarioName());
TreeNode child =null;
int childCount=0;
for(TestProcess tc : lstTestScenario)
{
childCount = childCount + 1;
ExecutionChildOrderValue.put(childCount, childCount);
child = new DefaultTreeNode(new TestProcess(tc.getTestScenarioName(), tc.getTestCaseName(), childCount, parentCount),parent);
System.out.println("TestCase (ROWKEY) :"+ child.getRowKey());
System.out.println("Scenario Name :" + tc.getTestScenarioName());
System.out.println("TestCases Name : " + tc.getTestCaseName());
System.out.println(" TestScenario ExecNo :" + tc.getTestScenarioExecNo());
System.out.println(" TestCase ExecNo :" + tc.getTestCaseExecNo());
}
System.out.println("");
System.out.println("");
}
return root1;
}
If i want to loop root1 object and print data in console, How to do ?
Actually, I want to loop through root1 and get the data from tree and wanted to store in db. But i am not getting and idea how to loop root1 object and get data printed on console.
Could anyone help me on this ?
Thanks
Neeraj

Related

Displaying data from SQLite table's columns, one of which holds an array

I managed to retrieve the SQLite table with only the first item of the array and put it in the UI's TextView. Couldn't get all the of the array's items. From each of the rest of the columns, a single value is returned successfully.
The JSON is parsed and passed as a parcelable ArrayList to a Fragment where it's presented in a list. Clicking on a list item directs to another Fragment where all the of item's details are presented.
I've been trying to write a for loop that returns the Strings in the array into the TextView, but the condition i < genresList.size() is always false. I tried using a while loop, but it returns only the first item of the list.
Various ways I've found on the internet didn't work.
Thanks.
Parsing and insertion to SQLite
private void parseJsonAndInsertToSQLIte(SQLiteDatabase db) throws JSONException {
// parsing the json
String jsonString = getJsonFileData();
JSONArray moviesArray = new JSONArray(jsonString);
ContentValues insertValues;
for (int i = 0; i < moviesArray.length(); i++) {
JSONObject jsonObject = moviesArray.getJSONObject(i);
String title = jsonObject.getString("title");
String imageUrl = jsonObject.getString("image");
String rating = jsonObject.getString("rating");
String releaseYear = jsonObject.getString("releaseYear");
JSONArray genresArray = jsonObject.getJSONArray("genre");
List<String> genres = new ArrayList<>();
for (int k = 0; k < genresArray.length(); k++) {
genres.add(genresArray.getString(k));
}
insertValues = new ContentValues();
insertValues.put(Movie.TITLE, title);
insertValues.put(Movie.IMAGE_URL, imageUrl);
insertValues.put(Movie.RATING, rating);
insertValues.put(Movie.RELEASE_YEAR, releaseYear);
for (int k = 0; k < genresArray.length(); k++) {
insertValues.put(Movie.GENRE, genres.get(k));
}
Log.i(TAG, "insertValues: " + genresArray);
long res = db.insert(TABLE_NAME, null, insertValues);
Log.i(TAG, "parsed and inserted to sql - row: " + res);
}
}
The item's details Fragment
public class MovieDetailsFragment extends Fragment{
... variables declarations come here...
#Nullable
#Override
public View onCreateView(#NotNull LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_details_movie, container, false);
Context context = getActivity();
Bundle idBundle = getArguments();
if (idBundle != null) {
movieId = getArguments().getInt("id");
}
getDatabase = new GetDatabase(context);
getDatabase.open();
Cursor cursor = getDatabase.getMovieDetails(movieId);
... more irelevant code comes here...
titleView = rootView.findViewById(R.id.movieTtlId);
ratingView = rootView.findViewById(R.id.ratingId);
releaseYearView = rootView.findViewById(R.id.releaseYearId);
genreView = rootView.findViewById(R.id.genreID);
String titleFromSQLite = cursor.getString(cursor.getColumnIndex(Movie.TITLE));
String ratingFromSQLite = cursor.getString(cursor.getColumnIndex(Movie.RATING));
String releaseYearFromSQLite = cursor.getString(cursor.getColumnIndex(Movie.RELEASE_YEAR));
String genreFromSQLite;
if(cursor.moveToFirst()) {
do {
genreFromSQLite = cursor.getString(cursor.getColumnIndex(Movie.GENRE));
genres.add(genreFromSQLite);
} while (cursor.moveToNext());
}
else{
genreFromSQLite = cursor.getString(cursor.getColumnIndex(Movie.RELEASE_YEAR));
}
getDatabase.close();
//more irelevant code comes here
genreView.setText(genreFromSQLite);
genreView.setFocusable(false);
genreView.setClickable(false);
return rootView;
}
}
The method that returns the table from SQLite:
public ArrayList<Movie> getMovies() {
String[] columns = {
Movie.ID,
Movie.TITLE,
Movie.IMAGE_URL,
Movie.RATING,
Movie.RELEASE_YEAR,
Movie.GENRE
};
// sorting orders
String sortOrder =
Movie.RELEASE_YEAR + " ASC";
ArrayList<Movie> moviesList = new ArrayList<>();
Cursor cursor = db.query(TABLE_NAME, //Table to query
columns,
null,
null,
null,
null,
sortOrder);
if (cursor.moveToFirst()) {
do {
Movie movie = new Movie();
movie.setMovieId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Movie.ID))));
movie.setTitle(cursor.getString(cursor.getColumnIndex(Movie.TITLE)));
movie.setImageUrl(cursor.getString(cursor.getColumnIndex(Movie.IMAGE_URL)));
movie.setRating(cursor.getDouble(cursor.getColumnIndex(Movie.RATING)));
movie.setReleaseYear(cursor.getInt(cursor.getColumnIndex(Movie.RELEASE_YEAR)));
List<String> genreArray = new ArrayList<>();
while(cursor.moveToNext()){
String genre = cursor.getString(cursor.getColumnIndex(Movie.GENRE));
genreArray.add(genre);
}
movie.setGenre(Collections.singletonList(String.valueOf(genreArray)));
// Adding a movie to the list
moviesList.add(movie);
} while (cursor.moveToNext());
}
Log.d(TAG, "The movies list from sqlite: " + moviesList);
cursor.close();
db.close();
return moviesList;
}
I believe your issue is with :-
for (int k = 0; k < genresArray.length(); k++) {
insertValues.put(Movie.GENRE, genres.get(k));
}
That will result in just the last value in the loop being inserted as the key/column name (first parameter of the put) does not change (and probably can't as you only have the one column).
You could use :-
StringBuilder sb = new StringBuilder();
for (int k = 0; k < genresArray.length(); k++) {
if (k > 0) {
sb.append(",");
}
sb.append(genres.get(k));
}
insertValues.put(Movie.GENRE, sb.toString());
Note the above code is in-principle code. It has not been tested or run and may therefore contains errors.
This would insert all the data as a CSV into the GENRE column.
BUT that is not a very good way as far as utilising databases. It would be far better if the Genre's were a separate table and probably that a mapping table were used (but that should be another question).
This is going to cause you issues as well :-
if (cursor.moveToFirst()) {
do {
Movie movie = new Movie();
movie.setMovieId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Movie.ID))));
movie.setTitle(cursor.getString(cursor.getColumnIndex(Movie.TITLE)));
movie.setImageUrl(cursor.getString(cursor.getColumnIndex(Movie.IMAGE_URL)));
movie.setRating(cursor.getDouble(cursor.getColumnIndex(Movie.RATING)));
movie.setReleaseYear(cursor.getInt(cursor.getColumnIndex(Movie.RELEASE_YEAR)));
List<String> genreArray = new ArrayList<>();
while(cursor.moveToNext()){
String genre = cursor.getString(cursor.getColumnIndex(Movie.GENRE));
genreArray.add(genre);
}
movie.setGenre(Collections.singletonList(String.valueOf(genreArray)));
// Adding a movie to the list
moviesList.add(movie);
} while (cursor.moveToNext());
That is you move to the first row of the Cursor, extract some data MoveieId,Title ... ReleaseYear.
Then
a) if there any other rows you move to the next (which would be for a different Movie) and the next until you finally reached the last row adding elements to the genreArray.
or
b) If there is only the one row in the Cursor genreArray is empty.
You then add the 1 and only movie to the movieList and return.
1 move (row) in the Cursor will exist per movie and there is only the 1 GENRE column per movie. You have to extract the data in that column and then split the data into the genreArray without moving (see the previous fix that will create a CSV (note that would be messed up if the data contained commas)).
IF you used the previous fix and store the multiple genres as a CSV, then you could use :-
if (cursor.moveToFirst()) {
do {
Movie movie = new Movie();
movie.setMovieId(Integer.parseInt(cursor.getString(cursor.getColumnIndex(Movie.ID))));
movie.setTitle(cursor.getString(cursor.getColumnIndex(Movie.TITLE)));
movie.setImageUrl(cursor.getString(cursor.getColumnIndex(Movie.IMAGE_URL)));
movie.setRating(cursor.getDouble(cursor.getColumnIndex(Movie.RATING)));
movie.setReleaseYear(cursor.getInt(cursor.getColumnIndex(Movie.RELEASE_YEAR)));
List<String> genreArray = new List<>(Arrays.asList((cursor.getString(cursor.getColumnIndex(Movie.GENRE))).split(",",0)));
movie.setGenre(Collections.singletonList(String.valueOf(genreArray)));
// Adding a movie to the list
moviesList.add(movie);
} while (cursor.moveToNext());
Note the above code is in-principle code. It has not been tested or run and may therefore contains errors.

Read arbitrarily json data to a javafx treeview,and only show the first element of any array in it

I need to show a json file on a javafx treeview,the structure of the json is unknown.Like the web site: json viewer site
I show the tree for user to select path of a value(like xpath of xml),so if the json is too big,I only need to show the first element of any array in json.
for example,the original data is:
{
name:"tom",
schools:[
{
name:"school1",
tags:["maths","english"]
},
{
name:"school2",
tags:["english","biological"]
},
]
}
I want to show:
again:the structure of json is unknown,it is just one example.
There's no other option than recursively handling the json and create the TreeItem structure based on the element info.
(There's probably a better way of adding the symbols, but I didn't find appropriate icons.)
private static final String INPUT = "{\n"
+ " name:\"tom\",\n"
+ " schools:[\n"
+ " {\n"
+ " name:\"school1\",\n"
+ " tags:[\"maths\",\"english\"]\n"
+ " },\n"
+ " {\n"
+ " name:\"school2\",\n"
+ " tags:[\"english\",\"biological\"]\n"
+ " },\n"
+ " ]\n"
+ "}";
private static final Image JSON_IMAGE = new Image("https://i.stack.imgur.com/1slrh.png");
private static void prependString(TreeItem<Value> item, String string) {
String val = item.getValue().text;
item.getValue().text = (val == null
? string
: string + " : " + val);
}
private enum Type {
OBJECT(new Rectangle2D(45, 52, 16, 18)),
ARRAY(new Rectangle2D(61, 88, 16, 18)),
PROPERTY(new Rectangle2D(31, 13, 16, 18));
private final Rectangle2D viewport;
private Type(Rectangle2D viewport) {
this.viewport = viewport;
}
}
private static final class Value {
private String text;
private final Type type;
public Value(Type type) {
this.type = type;
}
public Value(String text, Type type) {
this.text = text;
this.type = type;
}
}
private static TreeItem<Value> createTree(JsonElement element) {
if (element.isJsonNull()) {
return new TreeItem<>(new Value("null", Type.PROPERTY));
} else if (element.isJsonPrimitive()) {
JsonPrimitive primitive = element.getAsJsonPrimitive();
return new TreeItem<>(new Value(primitive.isString()
? '"' + primitive.getAsString() + '"'
: primitive.getAsString(), Type.PROPERTY));
} else if (element.isJsonArray()) {
JsonArray array = element.getAsJsonArray();
TreeItem<Value> item = new TreeItem<>(new Value(Type.ARRAY));
// for (int i = 0, max = Math.min(1, array.size()); i < max; i++) {
for (int i = 0, max = array.size(); i < max; i++) {
TreeItem<Value> child = createTree(array.get(i));
prependString(child, Integer.toString(i));
item.getChildren().add(child);
}
return item;
} else {
JsonObject object = element.getAsJsonObject();
TreeItem<Value> item = new TreeItem<>(new Value(Type.OBJECT));
for (Map.Entry<String, JsonElement> property : object.entrySet()) {
TreeItem<Value> child = createTree(property.getValue());
prependString(child, property.getKey());
item.getChildren().add(child);
}
return item;
}
}
#Override
public void start(Stage primaryStage) {
JsonParser parser = new JsonParser();
JsonElement root = parser.parse(INPUT);
TreeItem<Value> treeRoot = createTree(root);
TreeView<Value> treeView = new TreeView<>(treeRoot);
treeView.setCellFactory(tv -> new TreeCell<Value>() {
private final ImageView imageView;
{
imageView = new ImageView(JSON_IMAGE);
imageView.setFitHeight(18);
imageView.setFitWidth(16);
imageView.setPreserveRatio(true);
setGraphic(imageView);
}
#Override
protected void updateItem(Value item, boolean empty) {
super.updateItem(item, empty);
if (empty || item == null) {
setText("");
imageView.setVisible(false);
} else {
setText(item.text);
imageView.setVisible(true);
imageView.setViewport(item.type.viewport);
}
}
});
final Scene scene = new Scene(treeView);
primaryStage.setScene(scene);
primaryStage.show();
}

get Direction and get path android studio

i am trying to choose form the autocomplete a place and drew a path to it and when i pick a place from the autocomplete the app crashes.
please see the
--------- beginning of crash
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.saoutimohamed.tewsila, PID: 5924
java.lang.IllegalStateException: no included points
at com.google.android.gms.common.internal.Preconditions.checkState(Unknown
Source:8)
at com.google.android.gms.maps.model.LatLngBounds$Builder.build(Unknown
Source:10)
at com.saoutimohamed.tewsila.WelcomeDriver$4.onResponse(WelcomeDriver.java:271)
at retrofit2.ExecutorCallAdapterFactory$ExecutorCallbackCall$1$1.run(ExecutorCallAdapterFactory.java:70)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6938)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
Application terminated.
logcat and tall me what is wrong with my code
and this is the code
private void getDirection() {
String requestApi;
try {
requestApi = "https://maps.googleapis.com/maps/api/directions/json?" +
"mode=driving&" +
"transit_routing_preference=less_driving&" +
"origin=" + Common.mLastLocation.getLatitude() + "," + Common.mLastLocation.getLongitude() + "&" +
"destination=" + lat+","+lng + "&" +
"key=" + getResources().getString(R.string.google_direction_api);
Log.d("SAOUTI", requestApi);
mService.getPath(requestApi)
.enqueue(new Callback<String>() {
#Override
public void onResponse(Call<String> call, Response<String> response) {
try {
JSONObject jsonObject = new JSONObject(response.body().toString());
JSONArray jsonArray = jsonObject.getJSONArray("routes");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject route = jsonArray.getJSONObject(i);
JSONObject poly = route.getJSONObject("overview_polyline");
String polyline = poly.getString("points");
polyLineList = decodePoly(polyline);
}
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng latLng : polyLineList)
builder.include(latLng);
LatLngBounds bounds = builder.build();
CameraUpdate mCameraUpdate = CameraUpdateFactory.newLatLngBounds(bounds, 5);
mMap.animateCamera(mCameraUpdate);
polylineOptions = new PolylineOptions();
polylineOptions.color(Color.GRAY);
polylineOptions.width(5);
polylineOptions.startCap(new SquareCap());
polylineOptions.endCap(new SquareCap());
polylineOptions.jointType(JointType.ROUND);
polylineOptions.addAll(polyLineList);
greyPolyline = mMap.addPolyline(polylineOptions);
blackPolylineOptions = new PolylineOptions();
blackPolylineOptions.color(Color.BLACK);
blackPolylineOptions.width(5);
blackPolylineOptions.startCap(new SquareCap());
blackPolylineOptions.endCap(new SquareCap());
blackPolylineOptions.jointType(JointType.ROUND);
blackPolyline = mMap.addPolyline(blackPolylineOptions);
mMap.addMarker(new MarkerOptions()
.position(polyLineList.get(polyLineList.size() - 1))
.title("Pickup Location"));
ValueAnimator polyLineAnimator = ValueAnimator.ofInt(0, 100);
polyLineAnimator.setDuration(2000);
polyLineAnimator.setInterpolator(new LinearInterpolator());
polyLineAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
List<LatLng> points = greyPolyline.getPoints();
int percentValue = (int) valueAnimator.getAnimatedValue();
int size = points.size();
int newPoints = (int) (size * (percentValue / 100.0f));
List<LatLng> p = points.subList(0, newPoints);
blackPolyline.setPoints(p);
}
});
polyLineAnimator.start();
carMarker = mMap.addMarker(new MarkerOptions().position(currentPosition)
.flat(true)
.icon(BitmapDescriptorFactory.fromResource(R.mipmap.tewsila_car)));
handler = new Handler();
} catch (JSONException e) {
e.printStackTrace();
index = -1;
next = 1;
handler.postDelayed(drawPathRunnable, 3000);
}
}
#Override
public void onFailure(Call<String> call, Throwable t) {
Toast.makeText(WelcomeDriver.this, "" + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
the line that not responding in the logcat is (LatLngBounds bounds = builder.build();)
I had this same issue and i removed
"+getResources().getString(R.string.google_direction_api)" part from the requestApi. Perfectlr worked for me. But i don't know the reason.
requestApi = "https://maps.googleapis.com/maps/api/directions/json?" +
"mode=driving&" +
"transit_routing_preference=less_driving&" +
"origin=" + Common.mLastLocation.getLatitude() + "," + Common.mLastLocation.getLongitude() + "&" +
"destination=" + lat+","+lng + "&" +
"key=";

Facebook deserializing

I need help deserializing the JSON i get back from facebook.
I've been trying numerous ways to parse it but no success.
The only thing i seem to be parsing is the number of friends who have highscores, which is 2 :
The issue comes when I try to parse the name and score of the people in the json.
InvalidCastException: Cannot cast from source type to destination type.
I/Unity (21869): at FacebookScript.GETCallback (IGraphResult result) [0x00000] in <filename unknown>:0
I/Unity (21869): at Facebook.Unity.AsyncRequestString+<Start>c__Iterator1.MoveNext () [0x00000] in <filename unknown>:0
The raw result which I recieve (seen from logcat):
Raw:{"data":[{"score":60,"user":{"name":"JOHNY JOHN","id":"0000000000000"}},{"score":50,"user":{"name":"JOHN JOHN","id":"0000000000000"}}]}
Here is my code:
public void GETCallback(IGraphResult result)
{
if (result.ResultDictionary != null)
{
Debug.Log("Raw:" + result.RawResult);
var dict = Json.Deserialize(result.RawResult) as Dictionary<string, object>;
var friendList = new List<object>();
friendList = (List<object>)(dict["data"]);
int _friendCount = friendList.Count;
Debug.Log("Items found:" + _friendCount);
List<string> friendIDsFromFB = new List<string>();
/*for (int i = 0; i < _friendCount; i++) // Tried this, same error.
{
foreach(KeyValuePair<string, object> entry in friendList)
{
Debug.Log(entry.Key + "|" + entry.Value);
}
string friendFBID = getDataValueForKey((Dictionary<string, object>)(friendList[i]), "id");
string friendName = getDataValueForKey((Dictionary<string, object>)(friendList[i]), "name");
Debug.Log(i + "/" + _friendCount + "|" + friendFBID +"|"+ friendName);
NPBinding.UI.ShowToast(i + "/" + _friendCount + "|" + friendFBID + "|" + friendName, VoxelBusters.NativePlugins.eToastMessageLength.LONG);
//friendIDsFromFB.Add(friendFBID);
}*/
foreach(KeyValuePair<string, object> entry in friendList) // Tried this, same error.
{
Debug.Log(entry.Key + "|" + entry.Value);
}
}
else
{
NPBinding.UI.ShowToast("result.ResultDictionary is null", VoxelBusters.NativePlugins.eToastMessageLength.LONG);
}
}
private string getDataValueForKey(Dictionary<string, object> dict, string key)
{
object objectForKey;
if (dict.TryGetValue(key, out objectForKey))
{
return (string)objectForKey;
}
else {
return "";
}
}
I'm assuming that you're using MiniJSON (at least the version that used to come with the FB SDK)
N.B. Not tested for typos. Typing straight here in SO
var dict = Json.Deserialize(result.RawResult) as Dictionary<string, object>;
var datas = (List<object>)dict["data"];
foreach(var iterator in datas) {
var data = iterator as Dictionary<string, object>;
Debug.Log("Score is :: "+data["score"]);
//var score = int.Parse((string)data["score"]); //Parse to int after casting to string if you want the value
var userData = data["user"] as Dictionary<string, object>;
Debug.Log("Name is :: "+userData["name"]);
Debug.Log("ID is :: "+userData["id"]);
//var name = (string)userData["name"]; //Get the name
//var id = (string)userData["id"]; //...and the ID
}

Processing OOP connecting to MySQL database

a friend and I are trying to write a program in Processing. The program needs to be able to connect to our MySQL database pull information at random and display it. we have gotten that much to work. with the following code
import de.bezier.data.sql.*;
MySQL dbconnection;
void setup()
{
size( 100, 100 );
String user = "username";
String pass = "password";
// name of the database to use
String database = "databasename";
// name of the table that will be created
//
String table = "tablename";
//
dbconnection = new MySQL( this, "ip", database, user, pass );
if ( dbconnection.connect() )
{
// now read it back out
//
dbconnection.query( "SELECT COUNT(id) FROM quiz_table" );
dbconnection.next();
int NumberOfRows = dbconnection.getInt(1);
float random = random(1, NumberOfRows);
int roundrandom = round(random);
println(" Row Number: " + roundrandom );
dbconnection.query( "SELECT * FROM quiz_table WHERE id =" + roundrandom);
while (dbconnection.next())
{
int n = dbconnection.getInt("id");
String a = dbconnection.getString("name");
String c = dbconnection.getString("charactor");
String m = dbconnection.getString("game");
int y = dbconnection.getInt("year");
String q= dbconnection.getString("quote");
println(n + " " + a + " " + c + " " + m + " " + y + " " + q);
}
}
else
{
// connection failed !
}
}
void draw()
{
// i know this is not really a visual sketch ...
}
this seems to work fine. however we plan to make the program preform many more tasks and to keep things more manageable we wanted to make somethings objects in this case i want to make an object that will connect to the database when its called. The following is what i have come up with but despite reworking several ways I can't quite get it to work.
import de.bezier.data.sql.*;
MySQL dbconnection;
connect1 myCon;
void setup()
{
size(300,300);
myCon = new connect1("username","password","database","table");
myCon.dbconnect();
}
void draw()
{
}
class connect1 {
String user;
String pass;
String data;
String table;
connect1(String tempuser, String temppass, String tempdata, String temptable) {
user = tempuser;
pass = temppass;
data = tempdata;
table = temptable;
}
void dbconnect(){
dbconnection = new MySQL( this, "ip", data, user, pass );
if ( dbconnection.connect() )
{
// now read it back out
dbconnection.query( "SELECT COUNT(id) FROM table" );
dbconnection.next();
int NumberOfRows = dbconnection.getInt(1);
float random = random(1, NumberOfRows);
int roundrandom = round(random);
println(" Row Number: " + roundrandom );
dbconnection.query( "SELECT * FROM table WHERE id =" + roundrandom);
while (dbconnection.next())
{
int n = dbconnection.getInt("id");
String a = dbconnection.getString("name");
String c = dbconnection.getString("charactor");
String m = dbconnection.getString("game");
int y = dbconnection.getInt("year");
String q= dbconnection.getString("quote");
println(n + " " + a + " " + c + " " + m + " " + y + " " + q);
}
}
else
{
println("fail");
}
}
//end of class
}
Sorry if that is at all hard to understand
The constructor of MySQL expects a PApplet as the first argument. When you call new MySQL(this inside your object, this does no longer refer to the main PApplet as it did in your first program.
The simplest way to fix this might be:
myCon.dbconnect(this); // send the PApplet as argument
...
void dbconnect(PApplet parent) {
dbconnection = new MySQL( parent, "ip", data, user, pass );
...
Another option would be to pass the PApplet to the constructor of your object, storing it in a property, and using that property when calling new MySQL.