Additional data in foreach
In my show function in which you can watch every single group, I load all articles with the same tags. And the article with the most votes will be displayed separately at the top. In addition, I indicate the average rating of the items in this group. This is how my function looks like:
public function show($id)
{
$group = group::find($id);
$tagIdArray = $group->tags->pluck('id')->all();
$mostvotedarticle = Article::where('type', 4)->whereIn('privacy', [1, 3])
->whereHas('tags', function($query) use ($tagIdArray) {
$query->whereIn('tags.id', $tagIdArray);
}, '>=', count($tagIdArray))
->orderByVotes()->first();
$articledown = Article::where('status', 1)->whereHas('tags', function($query) use ($tagIdArray) {
$query->whereIn('tags.id', $tagIdArray);
}, '>=', count($tagIdArray))->downVotesAll()->count();
$articleup = Article::where('status', 1)->whereHas('tags', function($query) use ($tagIdArray) {
$query->whereIn('tags.id', $tagIdArray);
}, '>=', count($tagIdArray))->upVotesAll()->count();
$ratio = null;
if($articleup + $articledown == 0) {
$ratio = 0;
} else {
$ratio = ($articleup*100)/($articleup + $articledown);
}
return view('singlegroup',compact('groups','mostvotedarticle', 'ratio'));
}
On a overview page, the individual groups are displayed with a foreach loop:
@foreach ($groups as $group)
{{$group->name}}
<img src="-----load mostvotedarticle that is in this group------" alt="" />
<div class="progress-bar-primary" style="width:{{$ratio}}%;">
@endforeach
How can I have the mostvotedarticle and group ratings displayed in the foreach loop?
This is my previous index function:
public function index()
{
$user = Auth::user();
$groups = $user->groups()->latest()->with('tags')->paginate(20);
return view('groups', compact('groups'));
}
See also questions close to this topic
-
Laravel FFMpeg encoding failed
I'm using Laravel FFMpeg to encode videos and create thumbnails, but none of them are working. Whenever I try to create a thumbnail or encode a video I get following error:
ffmpeg failed to execute command '/usr/local/bin/ffmpeg' '-y' '-i' '/home/diego/dynamic4/bg/storage/app/public/activity/4942/cLCbKyLiGqbOb0M5JDtvNXUdzSxFGj9ts6sDZb4D.mp4' '-threads' '12' '-vcodec' 'libx264' '-acodec' 'libfaac' '-b:v' '1000k' '-refs' '6' '-coder' '1' '-sc_threshold' '40' '-flags' '+loop' '-me_range' '16' '-subq' '7' '-i_qfactor' '0.71' '-qcomp' '0.6' '-qdiff' '4' '-trellis' '1' '-b:a' '128k' '-pass' '1' '-passlogfile' '/tmp/ffmpeg-passes5c6378517cace4u1cg/pass-5c6378517cb33' '/home/diego/dynamic4/bg/storage/app/public/1234.mp4'
If I check that error on console I get this:
ffmpeg failed to execute command '/usr/local/bin/ffmpeg' '-y' '-i' '/home/diego/dynamic4/bg/storage/app/public/activity/4942/cLCbKyLiGqbOb0M5JDtvNXUdzSxFGj9ts6sDZb4D.mp4' '-threads' '12' '-vcodec' 'libx264' '-acodec' 'libfaac' '-b:v' '1000k' '-refs' '6' '-coder' '1' '-sc_threshold' '40' '-flags' '+loop' '-me_range' '16' '-subq' '7' '-i_qfactor' '0.71' '-qcomp' '0.6' '-qdiff' '4' '-trellis' '1' '-b:a' '128k' '-pass' '1' '-passlogfile' '/tmp/ffmpeg-passes5c6377a214b41rk6ao/pass-5c6377a214b7b' '/tmp/laravel-ffmpegObuaI1.mp4' ffmpeg version 4.1-1~18.04.york1 Copyright (c) 2000-2018 the FFmpeg developers built with gcc 7 (Ubuntu 7.3.0-27ubuntu1~18.04) configuration: --prefix=/usr --extra-version='1~18.04.york1' --toolchain=hardened --libdir=/usr/lib/x86_64-linux-gnu --incdir=/usr/include/x86_64-linux-gnu --arch=amd64 --enable-gpl --disable-stripping --enable-avresample --disable-filter=resample --enable-avisynth --enable-gnutls --enable-ladspa --enable-libaom --enable-libass --enable-libbluray --enable-libbs2b --enable-libcaca --enable-libcdio --enable-libcodec2 --enable-libflite --enable-libfontconfig --enable-libfreetype --enable-libfribidi --enable-libgme --enable-libgsm --enable-libjack --enable-libmp3lame --enable-libmysofa --enable-libopenjpeg --enable-libopenmpt --enable-libopus --enable-libpulse --enable-librsvg --enable-librubberband --enable-libshine --enable-libsnappy --enable-libsoxr --enable-libspeex --enable-libssh --enable-libtheora --enable-libtwolame --enable-libvidstab --enable-libvorbis --enable-libvpx --enable-libwavpack --enable-libwebp --enable-libx265 --enable-libxml2 --enable-libxvid --enable-libzmq --enable-libzvbi --enable-lv2 --enable-omx --enable-openal --enable-opengl --enable-sdl2 --enable-nonfree --enable-libfdk-aac --enable-libdc1394 --enable-libdrm --enable-libiec61883 --enable-chromaprint --enable-frei0r --enable-libx264 --enable-shared libavutil 56. 22.100 / 56. 22.100 libavcodec 58. 35.100 / 58. 35.100 libavformat 58. 20.100 / 58. 20.100 libavdevice 58. 5.100 / 58. 5.100 libavfilter 7. 40.101 / 7. 40.101 libavresample 4. 0. 0 / 4. 0. 0 libswscale 5. 3.100 / 5. 3.100 libswresample 3. 3.100 / 3. 3.100 libpostproc 55. 3.100 / 55. 3.100 Input #0, mov,mp4,m4a,3gp,3g2,mj2, from '/home/diego/dynamic4/bg/storage/app/public/activity/4942/cLCbKyLiGqbOb0M5JDtvNXUdzSxFGj9ts6sDZb4D.mp4': Metadata: major_brand : mp42 minor_version : 1 compatible_brands: mp41mp42isom creation_time : 2018-10-22T15:38:46.000000Z Duration: 00:00:58.36, start: 0.000000, bitrate: 1400 kb/s Stream #0:0(und): Video: h264 (Baseline) (avc1 / 0x31637661), yuv420p(tv, bt709), 848x480, 1334 kb/s, 30.01 fps, 30 tbr, 600 tbn, 1200 tbc (default) Metadata: creation_time : 2018-10-22T15:38:46.000000Z handler_name : Core Media Video Stream #0:1(und): Audio: aac (LC) (mp4a / 0x6134706D), 44100 Hz, stereo, fltp, 62 kb/s (default) Metadata: creation_time : 2018-10-22T15:38:46.000000Z handler_name : Core Media Audio [NULL @ 0x55fecc7a0280] Unable to find a suitable output format for 'failed' failed: Invalid argument
I have checked permissions and everything looks ok. I have also checked the video I'm trying to encode exists. It does, and apparently it get properly loaded. It seems to fail when trying to save encoded file. I spent one day doing research, I tried with different audio & video encoding, different routes and filesystems, but I couldn't make it work. I have also tried to check that passlogfile (
/tmp/ffmpeg-passes5c6377a214b41rk6ao/pass-5c6377a214b7b
) but as it gets stored under/tmp
I can't gain access to it.Any help much appreciated, thanks!
-
Laravel: Jobs failed - SQLSTATE[42S02]: Base table or view not found
I'm developing a Multi Tenant with Laravel v5.7 and I'm successful in sending queue emails, since my models have the property 'connection' defined.
But when trying to send, for example, an email using the Jobs class, the same fails and informs that the table of model does not exist.
From what error recorded in the table 'failed_jobs', even with the property 'connection' defined, it appears that the Job nevertheless tries to connect to the main database and not to the specified database of the property.
Is there any way to specify in Job which database to use, since the same is informed in the model?
database.php
'connections' => [ 'others' => ['...'] 'TENANT001' => [ 'driver' => 'mysql', 'database' => env('TENANT001_DATABASE', ''), 'host' => env('TENANT001_HOSTNAME', ''), 'port' => env('DB_PORT', '3306'), 'username' => env('TENANT001_USERNAME', 'forge'), 'password' => env('TENANT001_PASSWORD', ''), 'unix_socket' => env('DB_SOCKET', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ],
],
Sample Model
class Template extends Model { /** * The database name used by the model. * * @var string */ protected $connection = 'TENANT001'; }
failed_jobs
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'main_database.templates' doesn't exist in /www/samba/laravel.local/vendor/laravel/framework/src/Illuminate/Database/Connection.php:326
-
404 no errors displaying in laravel, how can I debug this/fix this update route?
I have created a has many relationships with a task model (many tasks to 1 project model) and set up a button to say if a task has been completed or not (1 or 0).
When I click the button to update the database with (as shown in the view) I receive this 404 instead (See pic) instead of the usual error screen which laravel usually throws out, checked the logs no errors there either.
I have attached the code and the network error that comes with the 404 but I don't really know what I am looking for in there if someone can point me in the right direction with 404 error or if there is a mistake in the code below, I would be most grateful!
view
<form method="POST" action="/tasks/{{ $task->id }}"> @method('PATCH') @csrf <label for="completed"> <input type="checkbox" name="completed" onChange="this.form.submit()"> {{ $task->description }} </label> </form>
Controller
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Task; class ProjectTasksController extends Controller { public function update() { dd('foo'); } }
Route
Route::patch('/tasks/{$task}', 'ProjectTasksController@update');
Migration
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateTasksTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('tasks', function (Blueprint $table) { $table->increments('id'); $table->unsignedInteger('project_id'); $table->string('description'); $table->boolean('completed')->default(false); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('tasks'); } }
Model
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Task extends Model { protected $fillable = [ 'project_id', 'description', 'completed' ]; public function project() { return $this->belongsTo(Project::class); } }
-
Data cannot be assigned
Hello why in this function data could not be read(assigned)? Error is in the line with comments(Object reference not set to an instance of an object.)
protected static int[][] GetMapFromFile(ref int size) { using (StreamReader sr = new StreamReader(@"C:\Users\doman\OneDrive\Desktop\Antras semestras\Programavimas\Laboras1\Laboras1\Duomenys.txt")) { string skyr = " ,.;"; size = Convert.ToInt32(sr.ReadLine()); int[][] map = new int[size][]; for (int i = 0; i < size; i++) { string line = sr.ReadLine(); string[] values = line.Split(skyr.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); for (int j = 0; j < values.Length; j++) { map[i][j] = Convert.ToInt32(values[j]); // Error here Console.Write(map[i][j]); } Console.WriteLine(); } return map; } }
My data file
5
0 1 3 4 2
1 0 4 2 6
3 4 0 7 1
4 2 7 0 7
2 6 1 7 0 -
Jave Type Parameter Method and Constructor Problem
I have these classes: - Class A is an interface with only one Abstract Method "M1" with a type parameter - Class B implements A - Class C is abstract class - Class D extends Class C
On class B i Override Method M1 and tries to create an C objects but its not working
public interface A{ public abstract <R> void M1(int a, int b, R ress); } public class B implements A{ public <B> void M1(int a, int b, B ress){ D itsd = new D(int a, int b, ress); } } public abstract class C{ int a, b; public C(int a, int b){ this.a=a; this.b=b; } } public class D extends C{ B c; public D(int a, int b, B c){ super(a, b); this.c=c; } }
Im getting a error with this suggestion : Change Constructor D(int a, int b, B c) to D(int a, int b, B c) idk why, Im sorry if this problem seems obvious to you but im new to all this Typed Method
-
Iterator Fault C++ when calling an auxiliary function
I'm having a strange iterator fault when calling the function distance(Point, Point) from Main.
Every point value is correctly stored though, I'm having issues calling distance function from main.
What can be wrong in my code? Maybe is because distance, once called, is refering to something out of its scope?
I attach main.cpp, triangle.h, triangle.cpp
main.cpp
#include <iostream> #include <cstdlib> #include "triangle.h" using namespace std; /* * */ int main(int argc, char** argv) { cout << "Hello!" << endl; Point P1(2,3); Point P2(5,8); Point P3(1,1); float d = distance(P1, P2); Triangle T1(P1, P2, P3); cout << "perimeter is " << T1.perimeter() << "\n" << endl; cout << "perimeter is " << T1.v1.get_x() << "\n" << endl; cout << "perimeter is " << T1.v1.get_y() << "\n" << endl; cout << "perimeter is " << T1.v2.get_x() << "\n" << endl; cout << "perimeter is " << T1.v2.get_y() << "\n" << endl; cout << "perimeter is " << T1.v3.get_x() << "\n" << endl; cout << "perimeter is " << T1.v3.get_y() << "\n" << endl; cout << "perimeter is " << d << "\n" << endl; return 0; }
triangle.cpp
#include <math.h> #include "triangle.h" float distance(Point v, Point w){ int p1x = v.get_x(); int p1y = v.get_y(); int p2x = w.get_x(); int p2y = w.get_y(); return sqrt((p2y-p1y)*(p2y-p1y) + (p2x-p1x)*(p2x-p1x)); } Point::Point(int a, int b){ x = a; y = b; } Point::Point(){ x = x; y = y; } void Point::set_values(int a, int b){ x = a; y = b; } int Point::get_x(){ return x; } int Point::get_y(){ return y; } Triangle::Triangle(Point a, Point b, Point c){ v1 = a; v2 = b; v3 = c; } float Triangle::area(){ return 1.0; } float Triangle::perimeter(){ return distance(v1, v2) + distance(v1, v3) + distance(v2, v3); }
triangle.h
#ifndef TRIANGLE_H #define TRIANGLE_H class Point { int x,y; public: void set_values(int, int); int get_x(); int get_y(); Point(int, int); Point(); }; class Triangle{ public: Point v1,v2,v3; Triangle(Point, Point, Point); float area(); float perimeter(); }; float distance(Point, Point); #endif /* TRIANGLE_H */
-
Why is forEach() faster than for...of – at least in V8 7.2?
array.forEach(ele => ...);
Seems to be significantly faster than
for (let ele of array) ...;
in Chrome 72, even though the former involves invoking a function in each iteration.
The result is similar in Safari 12.Why is this?
(for in-browser microbenchmark open jsben.ch/YaD9Q)
@MTCoster has created a jsperf.com/arr-iter-tests with a larger array size and got opposite results. However, here are mine:
-
how to dynamically reload part of document
For a filemanagement, i use ajax to send the data to php file. All data (reading files from directories) are outputted via
foreach
.Like:
foreach($files as $file ) { ... echo....filename, size, delete etc....
To appear the changes immediately after the ajax call, i reload parts of the html in my
success
like below:$.ajax({ url: "", type: "POST", data: new FormData(this), cache: false, contentType: false, processData: false, success: function(data) { $('.myStorage').load(document.URL + ' .calculateStorage'); $('.myFiles').load(document.URL + ' .table-responsive'); $('.breadcrumb').load(document.URL + ' form.crumbform');
So i use these
load()
-s for making the changes immediately visible for the user.The div
myFiles
is part of theforeach
loop which outputs the files.But i think this is not the correct way to do it because doing it this way, the complete foreach loop has to start again. But i am not sure how to handle with this so that changes after submit are immediately visible for the user. Is there another and better way to do it like this? And if so: how does it look like?
-
foreach loop results into email body
I want to send the results of a PowerShell
foreach
loop in the body of an email.The output of the variable gives me the table I want. I get this error message when I try to send the email.
Send-MailMessage : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Body'. Specified method is not supported.
function Invoke-MSSQLCommand { [CmdletBinding()] Param( [System.String]$ConnectionString, [System.String]$SQLCommand ) $V_cn = New-Object System.Data.SqlClient.SqlConnection("Data Source=$ConnectionString;Integrated Security=SSPI;Initial Catalog=master;Application Name=TEST_1;"); $V_cn.Open() $command_v = $V_cn.CreateCommand() $command_v.CommandText = $SQLCommand; $result_v = $command_v.ExecuteReader() $table_v = New-Object "System.Data.DataTable" "MyResultSet" $table_v.Load($result_v) $V_cn.Close(); $V_cn.Dispose(); return ,$table_v }; #function end $myobject = Invoke-MSSQLCommand -ConnectionString "server.domain,1433" -SQLCommand "Select [TimeStamp], [Computer Name] from something.dbo.table"; $emailrecipients = "user1@domain.com" $emailfrom = "Do_not_reply@domain.com" $message = foreach ($one in $myobject) { #$temp += "TimeStamp = " + $one.TimeStamp + " Computer Name = " + $one.'Computer Name' "TimeStamp = " + $one.TimeStamp + " Computer Name = " + $one.'Computer Name' + "`r " } $message Send-MailMessage -To $emailrecipients -Subject 'Awesome Subject Here' -Body $message -SmtpServer mail-server.net -Port 11 -From $emailfrom
-
OSError: ".txt" not found
I am trying this simple code to read data from a
.CSV
file, split and save it as several.txt
files, then load to test with following code:import pandas as pd import numpy as np data = pd.read_csv("C:/Users/m/Desktop/python/IRB3MAIZ9936-a.csv") #, sep="\s") del data['DATE'] matx = np.array(data.values, dtype= int) rows,cols = matx.shape count = 1 j = 25 for i in range(rows%25): matxx = matx[i%25:j , :] j += 25 np.savetxt(f' data{count}.txt ' , matxx, fmt='%d') count +=1 nn = np.loadtxt('data10.txt' , dtype = int) print()
But I get this error message:
Traceback (most recent call last): File "C:\Users\m\Desktop\python\read_csv.py", line 19, in <module> nn = np.loadtxt('data10.txt' , dtype = int) File "C:\ProgramData\Anaconda3\lib\site-packages\numpy\lib\npyio.py", line 926, in loadtxt fh = np.lib._datasource.open(fname, 'rt', encoding=encoding) File "C:\ProgramData\Anaconda3\lib\site-packages\numpy\lib\_datasource.py", line 262, in open return ds.open(path, mode, encoding=encoding, newline=newline) File "C:\ProgramData\Anaconda3\lib\site-packages\numpy\lib\_datasource.py", line 618, in open raise IOError("%s not found." % path) OSError: data10.txt not found. [Finished in 2.0s with exit code 1] [shell_cmd: python -u "C:\Users\m\Desktop\python\read_csv.py"] [dir: C:\Users\m\Desktop\python] [path: C:\ProgramData\Anaconda3;C:\ProgramData\Anaconda3\Library\mingw-w64\bin;C:\ProgramData\Anaconda3\Library\usr\bin;C:\ProgramData\Anaconda3\Library\bin;C:\ProgramData\Anaconda3\Scripts;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files (x86)\NVIDIA Corporation\PhysX\Common;C:\mingw64\bin;D:\cmake-3.11.3-win64-x64\cmake-3.11.3-win64-x64\bin;C:\opencv\build\install\x64\mingw\bin;C:\Program Files\nodejs\;C:\Program Files\MATLAB\R2018b\runtime\win64;C:\Program Files\MATLAB\R2018b\bin;C:\Program Files\Git\cmd;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\dotnet\;C:\Users\m\AppData\Local\Microsoft\WindowsApps;C:\Users\m\AppData\Roaming\npm;C:\Users\m\AppData\Local\Programs\Microsoft VS Code\bin]
What is the problem and how can I fix it?
-
How to do load balancing on Nginx and test if it works?
I read a lot of tutorials and Youtube videos on how to do this but I'm still stuck.
For example, my site link is https://52.80.233.150.
1) I only need 1 more server. (server 52.80.233.150:8001;) This means all requests for / go to the any of the servers listed under upstream. I came across this example on load balancing on this site here and edited the code. I pasted it into the nginx conf file inside the http tag. I'm not sure if this is correct.
http { upstream hec { server 52.80.233.150:8000; server 52.80.233.150:8001; } server { listen 80; server_name localhost; location / { proxy_pass http://hec; } }
Added the code here ^
server { listen 80 default_server; listen [::]:80 default_server; server_name localhost; root /usr/share/nginx/html; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location / { } # redirect server error pages to the static page /40x.html # error_page 404 /404.html; location = /40x.html { } # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { } # Settings for a TLS enabled server. # server { listen 443 ssl http2 default_server; listen [::]:443 ssl http2 default_server; server_name _; root /usr/share/nginx/html; ssl_certificate "/etc/ssl/private/nginx-selfsigned.crt"; ssl_certificate_key "/etc/ssl/private/nginx-selfsigned.key"; # It is *strongly* recommended to generate unique DH parameters # Generate them with: openssl dhparam -out /etc/pki/nginx/dhparams.pem 2048 ssl_dhparam "/etc/ssl/certs/dhparam.pem"; ssl_session_cache shared:SSL:1m; ssl_session_timeout 10m; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_ciphers HIGH:SEED:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!RSAPSK:!aDH:!aECDH:!EDH-DSS-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA:!SRP; ssl_prefer_server_ciphers on; # Load configuration files for the default server block. include /etc/nginx/default.d/*.conf; location / { proxy_redirect off; proxy_pass http://(confidential url); *##-req passed to another application* proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_read_timeout 86400; proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-NginX-Proxy true; }
2) How can I check if load balancing works? This is the code for the log. How can I see if it is actually routing the traffic?
log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main;
This is what comes up after I tried to do the load balancing. The command I used was: sudo tail -f /var/log/nginx/access.log. I refreshed the page 3 times. I want to see that it was alternating between the 2 servers. Everything is the same except for time.
(my IP Address) - - [14/Feb/2019:15:03:55 +0000] "GET / HTTP/2.0" 200 172 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36" "-" (my IP Address) - - [14/Feb/2019:15:03:58 +0000] "GET / HTTP/2.0" 200 172 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36" "-" (my IP Address) - - [14/Feb/2019:15:04:00 +0000] "GET / HTTP/2.0" 200 172 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36" "-"
I tried to add this line to the log format but the results are still the same.
'$server_name to $upstream_addr [$request] '
I guess the load balancing didn't work OR the log format is incorrect or maybe both.
-
GridView Taking Too Long To Load Data
I dont understand why my gridview is taking forever to load data.Any help will be highly appreciated. I am trying to load values into a DataAdapter if certain conditions are met and with values from firebase, it's working great but really taking long.
This is my initialization below
//Initialize Grid View for programming gridview = (GridView) view.findViewById(R.id.gridview); //Connect DataSet to Adapter lowerAdapter flowerAdapter = new lowerAdapter(getActivity(), ` mFlowerDataSet); //Now Connect Adapter To GridView gridview.setAdapter(flowerAdapter); //Add Listener For Grid View Item Click gridview.setOnItemClickListener(this);
And this here is the data set
//Creating Data Set By Adding flower objects private ArrayList<lower> prepareDataSet() { final ArrayList<lower> flowerData = new ArrayList<>(); jerrycanAmount = getActivity().getIntent().getExtras().getString("jerrycanAmount"); final String companyName = getActivity().getIntent().getExtras().getString("Tap"); getDistaances = FirebaseDatabase.getInstance().getReference().child("WaterPoints").child(companyName); final lower[] flower = new lower[1]; getDistaances.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { //Check if company offers smaal scale water if (dataSnapshot.child("smallscalecheck").exists()) { //Company does not offer small scale water check error.setVisibility(View.VISIBLE); errorImage.setVisibility(View.VISIBLE); relativeLayoutA.setVisibility(View.GONE); relativeLayoutB.setVisibility(View.VISIBLE); } else { getDistaances.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { if (!dataSnapshot.child("jerrycan").exists()) { //Data is not available relativeLayoutA.setVisibility(View.GONE); relativeLayoutB.setVisibility(View.VISIBLE); error.setVisibility(View.VISIBLE); error.setText("We couldn't find this data from this company"); errorImage.setVisibility(View.VISIBLE); } else { //Company Offers Small Scale Services final int jerrycanAmount = (Double.valueOf(dataSnapshot.child("jerrycan").getValue().toString())).intValue(); //1st Item flower[0] = new lower(); flower[0].setFlowerName("Ksh " + String.valueOf(jerrycanAmount)); flower[0].setPhotoPath(R.drawable.yellowjerrican); flowerData.add(flower[0]); //2nd Item flower[0] = new lower(); flower[0].setFlowerName("Dispensers"); flower[0].setPhotoPath(R.drawable.dispenser); flowerData.add(flower[0]); } } @Override public void onCancelled(DatabaseError databaseError) { Toast.makeText(getActivity(), databaseError.getMessage().toString(), Toast.LENGTH_SHORT).show(); } }); } } @Override public void onCancelled(DatabaseError databaseError) { Toast.makeText(getActivity(), databaseError.getMessage().toString(), Toast.LENGTH_SHORT).show(); } }); return flowerData; }