问:
I want to customize Xamarin MasterDetail (Xamarin Crossplatform project)
Just check the image below. I want to change the color of marked areas on the Image. The image is a screenshot of UWP application developed using xamarin forms cross platform project (PCL).
I am using MasterDetail page navigation.

Now Color is changed as per my first requirement.

Now what I want is a screen design like below

Now I am getting a result as below
Result of second screen ie, after navigating to stock entry page

Source Code

1. MasterDetailsPage.Xaml

```<code><?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="GST.Views.MasterDetailsPage"
             Title="Stock Manager"

                  MasterBehavior="SplitOnPortrait"
              BackgroundColor="#0063b1"
             xmlns:pages="clr-namespace:GST.Views;assembly=GST">

    <MasterDetailPage.Master >
        <pages:MasterDetailsPageMaster  x:Name="MasterPage" />
  </MasterDetailPage.Master>

    <MasterDetailPage.Detail>

        <NavigationPage >
      <x:Arguments>
        <pages:GST_Home  />

      </x:Arguments>
    </NavigationPage>
  </MasterDetailPage.Detail>
</MasterDetailPage>
</code>```

2. MasterDetailsPage.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace GST.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MasterDetailsPage : MasterDetailPage
    {
        public MasterDetailsPage()
        {
            InitializeComponent();
            MasterPage.ListView.ItemSelected += ListView_ItemSelected;
        }

        private void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            var item = e.SelectedItem as MasterDetailsPageMenuItem;
            if (item == null)
                return;

            var page = (Page)Activator.CreateInstance(item.TargetType);
            Detail.Title = item.Title;

            IsPresented = false;

             Detail.Navigation.PushAsync(page);

            MasterPage.ListView.SelectedItem = null;

        }
    }
}
</code>```

3. MasterDetailsPageDetail.xaml

```<code>     <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="GST.Views.MasterDetailsPageDetail"
             BackgroundColor="{StaticResource Key=background-color}"
               Title="Master GST Title Detailed" >
  <StackLayout Padding="10">
    <Label Text="This is a detail page. To get the 'triple' line icon on each platform add a icon to each platform and update the 'Master' page with an Icon that references it."/>
  </StackLayout>
</ContentPage>
</code>```

4.MasterDetailsPageDetail.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace GST.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MasterDetailsPageDetail : ContentPage
    {
        public MasterDetailsPageDetail()
        {
            InitializeComponent();

           // NavigationPage.SetHasBackButton(this, false);
            // NavigationPage.SetHasNavigationBar(this, false);
        }
    }
}
</code>```

5. MasterDetailsPageMaster.xaml

```<code> <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="GST.Views.MasterDetailsPageMaster"

             Title="Home">
  <StackLayout>
    <ListView x:Name="ListViewMenuItems"
              SeparatorVisibility="None"
              HasUnevenRows="true"
              ItemsSource="{Binding MenuItems}">
      <ListView.Header>
        <Grid BackgroundColor="#03A9F4">
          <Grid.ColumnDefinitions>
            <ColumnDefinition Width="10"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="10"/>
          </Grid.ColumnDefinitions>
          <Grid.RowDefinitions>
            <RowDefinition Height="30"/>
            <RowDefinition Height="80"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="10"/>
          </Grid.RowDefinitions>
          <Label
              Grid.Column="1"
              Grid.Row="2"
              Text="AppName"
              Style="{DynamicResource SubtitleStyle}"/>
        </Grid>
      </ListView.Header>
      <ListView.ItemTemplate>
        <DataTemplate>
          <ViewCell>
            <StackLayout Padding="15,10" HorizontalOptions="FillAndExpand">
              <Label VerticalOptions="FillAndExpand"
                    VerticalTextAlignment="Center"
                    Text="{Binding Title}"
                    FontSize="24"/>
            </StackLayout>
          </ViewCell>
        </DataTemplate>
      </ListView.ItemTemplate>
    </ListView>
  </StackLayout>
</ContentPage>
</code>```

6.MasterDetailsPageMaster.cs

```<code>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace GST.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MasterDetailsPageMaster : ContentPage
    {
        public ListView ListView => ListViewMenuItems;

        public MasterDetailsPageMaster()
        {
            InitializeComponent();
            BindingContext = new ViewModels.MasterDetailsPageMasterViewModel();

        }

    }
}
</code>```

7.MasterDetailsPageMenuItem.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GST.Views
{

    public class MasterDetailsPageMenuItem
    {
        public MasterDetailsPageMenuItem()
        {
            TargetType = typeof(MasterDetailsPageDetail);
        }
        public int Id { get; set; }
        public string Title { get; set; }

        public Type TargetType { get; set; }
    }
}
</code>```

8.GST_Home.xaml     -- Home Dash

```<code> <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             NavigationPage.HasNavigationBar="False"
             Title="Home Dash"
             x:Class="GST.Views.GST_Home">

    <StackLayout Padding="10">
        <Label Text="This is a detail page. To get the 'triple' line icon on each platform add a icon to each platform and update the 'Master' page with an Icon that references it."/>
    </StackLayout>
</ContentPage>
</code>```

9.GST_Home.cs

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace GST.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class GST_Home : ContentPage
    {
        public GST_Home()
        {
            InitializeComponent();
        }
    }
}
</code>```

If you want full source code please refer my code which is uploaded on Google Drive: https://drive.google.com/file/d/0B2XtD2dQvEhzb1NnNGdydG91S0k/view?usp=sharing

答:
If you wish to maintain the color of Title bar through out the app then you can write the following code inside the OnLaunched in the App.xaml.cs within Xamarin.UWP client project. For more please refer to Customizing Title Bar and Status Bar in Universal Windows Platform (UWP).

```<code>if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.ApplicationView"))
{
    var titleBar = ApplicationView.GetForCurrentView().TitleBar;
    if (titleBar != null)
    {
        titleBar.ButtonBackgroundColor = Colors.Red;
        titleBar.ButtonForegroundColor = Colors.White;
        titleBar.BackgroundColor = Colors.Red;
        titleBar.ForegroundColor = Colors.White;
    }
}
</code>```

And if you want to custom tool bar background color, you could set the BarBackgroundColor of the NavigationPage. You can do something like the following code.

```<code>private void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
 {
     ......

     var nav = new NavigationPage();
     nav.PushAsync(page);
     nav.BarBackgroundColor = Color.MediumPurple;
     Detail = nav;

 }
</code>```

Body:
Just check the image below. I want to change the color of marked areas on the Image. The image is a screenshot of UWP application developed using xamarin forms cross platform project (PCL).
I am using MasterDetail page navigation.

Now Color is changed as per my first requirement.

Now what I want is a screen design like below

Now I am getting a result as below
Result of second screen ie, after navigating to stock entry page

Source Code

1. MasterDetailsPage.Xaml

<?xml version="1.0" encoding="utf-8" ?>
<MasterDetailPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="GST.Views.MasterDetailsPage"
             Title="Stock Manager"

                  MasterBehavior="SplitOnPortrait"
              BackgroundColor="#0063b1"
             xmlns:pages="clr-namespace:GST.Views;assembly=GST">

    <MasterDetailPage.Master >
        <pages:MasterDetailsPageMaster  x:Name="MasterPage" />
  </MasterDetailPage.Master>

    <MasterDetailPage.Detail>

        <NavigationPage >
      <x:Arguments>
        <pages:GST_Home  />

      </x:Arguments>
    </NavigationPage>
  </MasterDetailPage.Detail>
</MasterDetailPage>

2. MasterDetailsPage.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace GST.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MasterDetailsPage : MasterDetailPage
    {
        public MasterDetailsPage()
        {
            InitializeComponent();
            MasterPage.ListView.ItemSelected += ListView_ItemSelected;
        }

        private void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            var item = e.SelectedItem as MasterDetailsPageMenuItem;
            if (item == null)
                return;

            var page = (Page)Activator.CreateInstance(item.TargetType);
            Detail.Title = item.Title;

            IsPresented = false;

             Detail.Navigation.PushAsync(page);

            MasterPage.ListView.SelectedItem = null;

        }
    }
}

3. MasterDetailsPageDetail.xaml

     <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="GST.Views.MasterDetailsPageDetail"
             BackgroundColor="{StaticResource Key=background-color}"
               Title="Master GST Title Detailed" >
  <StackLayout Padding="10">

  </StackLayout>
</ContentPage>

4.MasterDetailsPageDetail.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace GST.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MasterDetailsPageDetail : ContentPage
    {
        public MasterDetailsPageDetail()
        {
            InitializeComponent();

           // NavigationPage.SetHasBackButton(this, false);
            // NavigationPage.SetHasNavigationBar(this, false);
        }
    }
}

5. MasterDetailsPageMaster.xaml

 <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="GST.Views.MasterDetailsPageMaster"

             Title="Home">
  <StackLayout>
    <ListView x:Name="ListViewMenuItems"
              SeparatorVisibility="None"
              HasUnevenRows="true"
              ItemsSource="{Binding MenuItems}">
      <ListView.Header>
        <Grid BackgroundColor="#03A9F4">
          <Grid.ColumnDefinitions>
            <ColumnDefinition Width="10"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="10"/>
          </Grid.ColumnDefinitions>
          <Grid.RowDefinitions>
            <RowDefinition Height="30"/>
            <RowDefinition Height="80"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="10"/>
          </Grid.RowDefinitions>

        </Grid>
      </ListView.Header>
      <ListView.ItemTemplate>
        <DataTemplate>
          <ViewCell>
            <StackLayout Padding="15,10" HorizontalOptions="FillAndExpand">

            </StackLayout>
          </ViewCell>
        </DataTemplate>
      </ListView.ItemTemplate>
    </ListView>
  </StackLayout>
</ContentPage>

6.MasterDetailsPageMaster.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace GST.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class MasterDetailsPageMaster : ContentPage
    {
        public ListView ListView => ListViewMenuItems;

        public MasterDetailsPageMaster()
        {
            InitializeComponent();
            BindingContext = new ViewModels.MasterDetailsPageMasterViewModel();

        }

    }
}

7.MasterDetailsPageMenuItem.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GST.Views
{

    public class MasterDetailsPageMenuItem
    {
        public MasterDetailsPageMenuItem()
        {
            TargetType = typeof(MasterDetailsPageDetail);
        }
        public int Id { get; set; }
        public string Title { get; set; }

        public Type TargetType { get; set; }
    }
}

8.GST_Home.xaml     -- Home Dash

 <?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             NavigationPage.HasNavigationBar="False"
             Title="Home Dash"
             x:Class="GST.Views.GST_Home">

    <StackLayout Padding="10">

    </StackLayout>
</ContentPage>

9.GST_Home.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace GST.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class GST_Home : ContentPage
    {
        public GST_Home()
        {
            InitializeComponent();
        }
    }
}

If you want full source code please refer my code which is uploaded on Google Drive: https://drive.google.com/file/d/0B2XtD2dQvEhzb1NnNGdydG91S0k/view?usp=sharing

Body:
If you wish to maintain the color of Title bar through out the app then you can write the following code inside the OnLaunched in the App.xaml.cs within Xamarin.UWP client project. For more please refer to Customizing Title Bar and Status Bar in Universal Windows Platform (UWP).

if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.ApplicationView"))
{
    var titleBar = ApplicationView.GetForCurrentView().TitleBar;
    if (titleBar != null)
    {
        titleBar.ButtonBackgroundColor = Colors.Red;
        titleBar.ButtonForegroundColor = Colors.White;
        titleBar.BackgroundColor = Colors.Red;
        titleBar.ForegroundColor = Colors.White;
    }
}

And if you want to custom tool bar background color, you could set the BarBackgroundColor of the NavigationPage. You can do something like the following code.

private void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e)
 {
     ......

     var nav = new NavigationPage();
     nav.PushAsync(page);
     nav.BarBackgroundColor = Color.MediumPurple;
     Detail = nav;

 }


来源: stackexchange

问:
Roslyn get all object creations and its identifier name
I am looking for a solution to get all object creations inside a method. I came up with following solution to get a list of all creations:

```<code>var creations = MethodDeclaration.Body.DescendantNodes().OfType<ObjectCreationExpressionSyntax>();
</code>```

But now I am looking for the identifier name(variable name). While debugging I figured out, that this variable has this information - but the identifier property is no accessible.

```<code>creations.First().Parent.Parent.Identifier.ValueText;
</code>```

So i would be very pleased if someone has a solution for my problem.

EDIT

I am trying to analyze unittests. E.g.:

```<code>[TestMethod]
public void WarningOverReferencedTest()
{
    var myVar = new MyObject();
    var myVar1 = new MyObject1();
    var myVar2 = new MyObject2();
    var myVar3 = new MyObject();
    var myVar4 = new MyObject3();
    Assert.AreEqual(true, myVar.someProperty);
    Assert.AreEqual(true, myVar3.someProperty2);
    Assert.AreEqual(true, myVar1.someProperty);
    Assert.AreEqual(true, myVar2.someProperty);
}
</code>```

I want to count the references used in the Assert.AreEqual checks. So the example from above should return 3, because myVar and myVar3 are from the same type and myVar4 is not used in the Assert.AreEqual check.

答:
You need to cast creations.First().Parent.Parent to a Type that has an Identifier property - in your case it's most likely VariableDeclaratorSyntax - then you will be able to access its Identifier. This is of course dangerous because you might find an ObjectCreationSyntax whose grandparent is different.

Take a look at this example:

```<code>List<Person> people = new List<Person>() {
      new Person("Jim"),
      new Person("Frank")
};
</code>```

You'll successfully get the Identifier of the people ObjectCreation, but not its elements' (since they do not have a variable name at all). There are lots of corner cases to work around, with lots of possible solutions.

A dirty workaround would be to check if the grandparent is of kind VariableDeclarator and cast it only then. Maybe if you share what you are trying to accomplish (in the grand scheme of things) I can advice better.

EDIT

If I understood you correctly, you want to count the number of distinct types created in a method. ObjectCreationExpressionSyntax objects have a Type property, which shows what type of object is being created. This is exactly what you need, however getting the type itself is troublesome, but you can look at the names like so:

```<code>HashSet<ITypeSymbol> types = new HashSet<ITypeSymbol>();

foreach (ObjectCreationExpressionSyntax node in creations)
{
    var typeSymbol = semanticModel.GetTypeInfo(node).Type;
    types.Add(typeSymbol);
}
int numberOfTypes = types.Count;
</code>```

You can't just count the node.Type-s, becuase those are SyntaxNode-s, and will not be identical. But their symbol will be, and using a HashSet will ensure that you are getting no duplicates. You can get the SemanticModel object from the context if you use RegisterSemanticModelAction.

ContentLicense: CC BY-SA 3.0

Body:
I am looking for a solution to get all object creations inside a method. I came up with following solution to get a list of all creations:

var creations = MethodDeclaration.Body.DescendantNodes().OfType<ObjectCreationExpressionSyntax>();

But now I am looking for the identifier name(variable name). While debugging I figured out, that this variable has this information - but the identifier property is no accessible.

creations.First().Parent.Parent.Identifier.ValueText;

So i would be very pleased if someone has a solution for my problem.

EDIT

I am trying to analyze unittests. E.g.:

[TestMethod]
public void WarningOverReferencedTest()
{
    var myVar = new MyObject();
    var myVar1 = new MyObject1();
    var myVar2 = new MyObject2();
    var myVar3 = new MyObject();
    var myVar4 = new MyObject3();
    Assert.AreEqual(true, myVar.someProperty);
    Assert.AreEqual(true, myVar3.someProperty2);
    Assert.AreEqual(true, myVar1.someProperty);
    Assert.AreEqual(true, myVar2.someProperty);
}

I want to count the references used in the Assert.AreEqual checks. So the example from above should return 3, because myVar and myVar3 are from the same type and myVar4 is not used in the Assert.AreEqual check.

Body:
You need to cast creations.First().Parent.Parent to a Type that has an Identifier property - in your case it's most likely VariableDeclaratorSyntax - then you will be able to access its Identifier. This is of course dangerous because you might find an ObjectCreationSyntax whose grandparent is different.

Take a look at this example:

List<Person> people = new List<Person>() {
      new Person("Jim"),
      new Person("Frank")
};

You'll successfully get the Identifier of the people ObjectCreation, but not its elements' (since they do not have a variable name at all). There are lots of corner cases to work around, with lots of possible solutions.

A dirty workaround would be to check if the grandparent is of kind VariableDeclarator and cast it only then. Maybe if you share what you are trying to accomplish (in the grand scheme of things) I can advice better.

EDIT

If I understood you correctly, you want to count the number of distinct types created in a method. ObjectCreationExpressionSyntax objects have a Type property, which shows what type of object is being created. This is exactly what you need, however getting the type itself is troublesome, but you can look at the names like so:

HashSet<ITypeSymbol> types = new HashSet<ITypeSymbol>();

foreach (ObjectCreationExpressionSyntax node in creations)
{
    var typeSymbol = semanticModel.GetTypeInfo(node).Type;
    types.Add(typeSymbol);
}
int numberOfTypes = types.Count;

You can't just count the node.Type-s, becuase those are SyntaxNode-s, and will not be identical. But their symbol will be, and using a HashSet will ensure that you are getting no duplicates. You can get the SemanticModel object from the context if you use RegisterSemanticModelAction.


问:
How to pass optional values generated from dynamic Text Boxes to Database
I've a Form which dynamically populates textboxes depending on user requirements. I would like to fetch the values of those textboxes and pass it to Database.

View

I'm using Entity Framework where in I've created a Model to accept values from View.

```<code>    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Required]
    public int Id { get; set; }
    [Required]
    public List<string> Question { get; set; }
    [Required]
    public string Intent { get; set; }
    [Required]
    public string Entity { get; set; }
    [Required]
    public string Answer { get; set; }
</code>```

In this case my model is static. How will the Database map the values to columns from List<> ?

Ps : I'm using Code first approach!

答:
you can bind list of object to textboxs or any other control with name conventions by looping through the list and populating inputs with required name for example:

```<code>    @for (int i = 0; i < Model.Questions.Count; i++)
    {
    @Html.TextBoxFor(x=>Model.Questions[i])
    }
</code>```

or by this way

```<code>for(int i=0;i<Model.Questions.Count;i++)
{
<input type='text' name="Questions[@i]" />
}
</code>```

you can find more at:

https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding

http://www.c-sharpcorner.com/UploadFile/4b0136/introduction-to-model-binding-in-Asp-Net-mvc/

Body:
I've a Form which dynamically populates textboxes depending on user requirements. I would like to fetch the values of those textboxes and pass it to Database.

View

I'm using Entity Framework where in I've created a Model to accept values from View.

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Required]
    public int Id { get; set; }
    [Required]
    public List<string> Question { get; set; }
    [Required]
    public string Intent { get; set; }
    [Required]
    public string Entity { get; set; }
    [Required]
    public string Answer { get; set; }

In this case my model is static. How will the Database map the values to columns from List<> ?

Ps : I'm using Code first approach!

Body:
you can bind list of object to textboxs or any other control with name conventions by looping through the list and populating inputs with required name for example:

    @for (int i = 0; i < Model.Questions.Count; i++)
    {
    @Html.TextBoxFor(x=>Model.Questions[i])
    }

or by this way

for(int i=0;i<Model.Questions.Count;i++)
{
<input type='text' name="Questions[@i]" />
}

you can find more at:

https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding

http://www.c-sharpcorner.com/UploadFile/4b0136/introduction-to-model-binding-in-Asp-Net-mvc/


问:
Progress Dialog in AsyncTask generating error on Activity Reference. Not an enclosing class
I am trying to send some data to web database using AsyncTask but it gives me error in this line in preExecute method when i try to initialize progress dialog.
dialog = new ProgressDialog(MainActivity.this, R.style.CustomAlertDialogStyle)

Error about MainActivity.this saying "mainactivity is not an enclosing class".

Here is my full code.

```<code>package com.cplusplusapp.rashidfaheem.hybridsoftwaresolutions.hbss.rashidfaheem.webservice;

import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.HttpURLConnection;
import javax.net.ssl.HttpsURLConnection;

public class MainActivity extends AppCompatActivity {
Spinner sp;
Button signup, login;
EditText edtname, edtemail, edtaddress, edtpassword, edtphone, edtcity;
String name,pass,add,catagory,phone,email,city;
ArrayAdapter<String> adapter;
String[] options = {"Student", "Teacher"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    signup = (Button) findViewById(R.id.signup);
    login = (Button) findViewById(R.id.login);
    edtname = (EditText) findViewById(R.id.edtname);
    edtemail = (EditText) findViewById(R.id.edtemail);
    edtaddress = (EditText) findViewById(R.id.edtaddress);
    edtpassword = (EditText) findViewById(R.id.edtpassword);
    edtphone = (EditText) findViewById(R.id.edtphone);
    edtcity = (EditText) findViewById(R.id.edtcity);
    sp = (Spinner) findViewById(R.id.sp);

    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, options);
    sp.setAdapter(adapter);

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });

    signup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String permission="false";
            new adduser().execute(edtname.getText().toString(), edtemail.getText().toString(), edtpassword.getText().toString(),
                    edtcity.getText().toString(), edtphone.getText().toString(), edtaddress.getText().toString(), permission, sp.getSelectedItem().toString());
        }
    });
}
}

class adduser extends AsyncTask<String, String, String>{
Context mcontext;
ProgressDialog dialog;
HttpURLConnection conn;
URL url=null;

@Override
protected void onPreExecute() {
    super.onPreExecute();
    dialog = new ProgressDialog(MainActivity.this, R.style.CustomAlertDialogStyle);
    dialog.setMessage("Registering User, Please Wait");
    dialog.setCancelable(false);
    dialog.show();
}

@Override
protected String doInBackground(String... strings) {
    try{
        // Enter URL address where your php file resides
        url=new URL("http://127.0.0.1/rashid/signup.php");

    }catch (MalformedURLException e){
        e.printStackTrace();
    }

    try {

        // Setup HttpURLConnection class to send and receive data from php and mysql
        conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");

        // setDoInput and setDoOutput method depict handling of both send and receive
        conn.setDoInput(true);
        conn.setDoOutput(true);

        // Append parameters to URL
        Uri.Builder builder = new Uri.Builder();
        builder.appendQueryParameter("customer_name", strings[0]);
        builder.appendQueryParameter("customer_email", strings[1]);
        builder.appendQueryParameter("customer_pass", strings[2]);
        builder.appendQueryParameter("customer_city", strings[3]);
        builder.appendQueryParameter("customer_contact", strings[4]);
        builder.appendQueryParameter("customer_address", strings[5]);
        builder.appendQueryParameter("permission", strings[6]);
        builder.appendQueryParameter("category", strings[7]);

        String query = builder.build().getEncodedQuery();

        // Open connection for sending data
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
        writer.write(query);
        writer.flush();
        writer.close();

        conn.connect();

    } catch (IOException e){
        e.printStackTrace();
    } catch (Exception e){
        e.printStackTrace();
    }

    try{
        int code = conn.getResponseCode();

        // Check if successful connection made
        if (code== HttpsURLConnection.HTTP_OK){

            // Read data sent from server
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder result = new StringBuilder();
            String line;

            while ((line=reader.readLine())!=null){
                result.append(line);
            }
            // Pass data to onPostExecute method
            return (result.toString());
        } else {
            return ("unsuccessfull");
        }
    }catch (IOException e){
        e.printStackTrace();
        return ("Exception");
    } finally {
        conn.disconnect();
    }

}

@Override
protected void onPostExecute(String result) {
    dialog.dismiss();
    if (result.equalsIgnoreCase("true")){
        /* Here launching another activity when login successful. If you persist login state
            use sharedPreferences of Android. and logout button to clear sharedPreferences.
             */
        Toast.makeText(mcontext, "Registered Successfully", Toast.LENGTH_LONG).show();
    } else if (result.equalsIgnoreCase("false")){
        // If username and password does not match display a error message
        Toast.makeText(mcontext, "Register First", Toast.LENGTH_LONG).show();

    } else if (result.equalsIgnoreCase("Exception")|| result.equalsIgnoreCase("Unsuccessful")){
        Toast.makeText(mcontext, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).show();
    }
}
}
</code>```

答:
You are trying to access a class (MainActivity) that is inside it's own file from another class that is in its own file (adduser) . There is no way to do that - how is one class supposed to know about the other's instance magically? What you can do:

Move the AsyncTask so it is an inner class in MainActivity

Pass off your Activity to the AsyncTask (via its constructor) then acess using activityVariable.findViewById(); (I am using mActivity in the example below) Alternatively, your ApplicationContext (use proper naming convention, the A needs to be lowercase) is actually an instance of MainActivity you're good to go, so do ApplicationContext.findViewById();

Using the Constructor example:

```<code>public class adduser extends AsyncTask<Context, String, ArrayList<Card>>
{

Context ApplicationContext;
    Activity mActivity;

   public adduser (Activity activity)
   {
     super();
     mActivity = activity;
   }
</code>```

Body:
I am trying to send some data to web database using AsyncTask but it gives me error in this line in preExecute method when i try to initialize progress dialog.
dialog = new ProgressDialog(MainActivity.this, R.style.CustomAlertDialogStyle)

Error about MainActivity.this saying "mainactivity is not an enclosing class".

Here is my full code.

package com.cplusplusapp.rashidfaheem.hybridsoftwaresolutions.hbss.rashidfaheem.webservice;

import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.HttpURLConnection;
import javax.net.ssl.HttpsURLConnection;

public class MainActivity extends AppCompatActivity {
Spinner sp;
Button signup, login;
EditText edtname, edtemail, edtaddress, edtpassword, edtphone, edtcity;
String name,pass,add,catagory,phone,email,city;
ArrayAdapter<String> adapter;
String[] options = {"Student", "Teacher"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    signup = (Button) findViewById(R.id.signup);
    login = (Button) findViewById(R.id.login);
    edtname = (EditText) findViewById(R.id.edtname);
    edtemail = (EditText) findViewById(R.id.edtemail);
    edtaddress = (EditText) findViewById(R.id.edtaddress);
    edtpassword = (EditText) findViewById(R.id.edtpassword);
    edtphone = (EditText) findViewById(R.id.edtphone);
    edtcity = (EditText) findViewById(R.id.edtcity);
    sp = (Spinner) findViewById(R.id.sp);

    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, options);
    sp.setAdapter(adapter);

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });

    signup.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String permission="false";
            new adduser().execute(edtname.getText().toString(), edtemail.getText().toString(), edtpassword.getText().toString(),
                    edtcity.getText().toString(), edtphone.getText().toString(), edtaddress.getText().toString(), permission, sp.getSelectedItem().toString());
        }
    });
}
}

class adduser extends AsyncTask<String, String, String>{
Context mcontext;
ProgressDialog dialog;
HttpURLConnection conn;
URL url=null;

@Override
protected void onPreExecute() {
    super.onPreExecute();
    dialog = new ProgressDialog(MainActivity.this, R.style.CustomAlertDialogStyle);
    dialog.setMessage("Registering User, Please Wait");
    dialog.setCancelable(false);
    dialog.show();
}

@Override
protected String doInBackground(String... strings) {
    try{
        // Enter URL address where your php file resides
        url=new URL("http://127.0.0.1/rashid/signup.php");

    }catch (MalformedURLException e){
        e.printStackTrace();
    }

    try {

        // Setup HttpURLConnection class to send and receive data from php and mysql
        conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");

        // setDoInput and setDoOutput method depict handling of both send and receive
        conn.setDoInput(true);
        conn.setDoOutput(true);

        // Append parameters to URL
        Uri.Builder builder = new Uri.Builder();
        builder.appendQueryParameter("customer_name", strings[0]);
        builder.appendQueryParameter("customer_email", strings[1]);
        builder.appendQueryParameter("customer_pass", strings[2]);
        builder.appendQueryParameter("customer_city", strings[3]);
        builder.appendQueryParameter("customer_contact", strings[4]);
        builder.appendQueryParameter("customer_address", strings[5]);
        builder.appendQueryParameter("permission", strings[6]);
        builder.appendQueryParameter("category", strings[7]);

        String query = builder.build().getEncodedQuery();

        // Open connection for sending data
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), "UTF-8"));
        writer.write(query);
        writer.flush();
        writer.close();

        conn.connect();

    } catch (IOException e){
        e.printStackTrace();
    } catch (Exception e){
        e.printStackTrace();
    }

    try{
        int code = conn.getResponseCode();

        // Check if successful connection made
        if (code== HttpsURLConnection.HTTP_OK){

            // Read data sent from server
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder result = new StringBuilder();
            String line;

            while ((line=reader.readLine())!=null){
                result.append(line);
            }
            // Pass data to onPostExecute method
            return (result.toString());
        } else {
            return ("unsuccessfull");
        }
    }catch (IOException e){
        e.printStackTrace();
        return ("Exception");
    } finally {
        conn.disconnect();
    }

}

@Override
protected void onPostExecute(String result) {
    dialog.dismiss();
    if (result.equalsIgnoreCase("true")){
        /* Here launching another activity when login successful. If you persist login state
            use sharedPreferences of Android. and logout button to clear sharedPreferences.
             */
        Toast.makeText(mcontext, "Registered Successfully", Toast.LENGTH_LONG).show();
    } else if (result.equalsIgnoreCase("false")){
        // If username and password does not match display a error message
        Toast.makeText(mcontext, "Register First", Toast.LENGTH_LONG).show();

    } else if (result.equalsIgnoreCase("Exception")|| result.equalsIgnoreCase("Unsuccessful")){
        Toast.makeText(mcontext, "OOPs! Something went wrong. Connection Problem.", Toast.LENGTH_LONG).show();
    }
}
}

Body:
You are trying to access a class (MainActivity) that is inside it's own file from another class that is in its own file (adduser) . There is no way to do that - how is one class supposed to know about the other's instance magically? What you can do:

Move the AsyncTask so it is an inner class in MainActivity

Pass off your Activity to the AsyncTask (via its constructor) then acess using activityVariable.findViewById(); (I am using mActivity in the example below) Alternatively, your ApplicationContext (use proper naming convention, the A needs to be lowercase) is actually an instance of MainActivity you're good to go, so do ApplicationContext.findViewById();

Using the Constructor example:

public class adduser extends AsyncTask<Context, String, ArrayList<Card>>
{

Context ApplicationContext;
    Activity mActivity;

   public adduser (Activity activity)
   {
     super();
     mActivity = activity;
   }


问:
How to set property to String
So I've got a bunch of pictures in Resources, 3 pictures of Cat, Dog, and Mouse.
I have to ask the user for the animal they want to see, and then display the correct picture.
Currently I have something like this.

```<code>    Dim animal = InputBox("Enter an animal to show a picture of")
    PictureBox1.Image = My.Resources.animal
</code>```

But I can't set the property to the "animal" string.

How would I do this.

答:
You can use the ResourceManager class:

```<code>'Get the resource (it exists).
Dim Resource As Object = My.Resources.ResourceManager.GetObject(animal)

'Verify that the resource exists and that it is an, or derives from Image.
If Resource IsNot Nothing AndAlso GetType(Image).IsAssignableFrom(Resource.GetType()) Then
    PictureBox1.Image = DirectCast(Resource, Image) 'Cast the resource to an image and display it in the picture box.
End If
</code>```

Title: How to set property to String

Body:
So I've got a bunch of pictures in Resources, 3 pictures of Cat, Dog, and Mouse.
I have to ask the user for the animal they want to see, and then display the correct picture.
Currently I have something like this.

    Dim animal = InputBox("Enter an animal to show a picture of")
    PictureBox1.Image = My.Resources.animal

But I can't set the property to the "animal" string.

How would I do this.

Body:
You can use the ResourceManager class:

'Get the resource (it exists).
Dim Resource As Object = My.Resources.ResourceManager.GetObject(animal)

'Verify that the resource exists and that it is an, or derives from Image.
If Resource IsNot Nothing AndAlso GetType(Image).IsAssignableFrom(Resource.GetType()) Then
    PictureBox1.Image = DirectCast(Resource, Image) 'Cast the resource to an image and display it in the picture box.
End If


问:
RecyclerView doesn't load items on first start of activity
Everytime we open the activity that bares the recycler adapter it fails to load on the first try. Exiting the activity and re-entering fixes the problem. Here is a gif for example. https://gyazo.com/32dc664dd427ef1129704a09861a3708

The Item i am spawning in:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools"
    android:id="@+id/show_chat_single_item_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="70dp"

        app:cardBackgroundColor="#dcdada"
        app:cardCornerRadius="0dp"
        app:contentPadding="3dp"
        card_view:cardCornerRadius="5dp"
        card_view:cardElevation="2dp"
        card_view:cardUseCompatPadding="true">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/chat_persion_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginTop="8dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:srcCompat="@mipmap/ic_launcher" />

            <TextView
                android:id="@+id/chat_persion_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="0dp"
                android:text="Name"
                android:textSize="18sp"
                android:textStyle="bold"
                app:layout_constraintLeft_toRightOf="@+id/chat_persion_image"
                app:layout_constraintTop_toTopOf="@+id/chat_persion_image" />

            <TextView
                android:id="@+id/chat_persion_email"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="0dp"
                android:layout_marginTop="8dp"
                android:text="Email"
                app:layout_constraintLeft_toLeftOf="@+id/chat_persion_name"
                app:layout_constraintTop_toBottomOf="@+id/chat_persion_name" />
        </android.support.constraint.ConstraintLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>
</code>```

My conversation layout:

```<code><?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/msgs_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        app:theme="@style/AppTheme2"

        >

        <android.support.v7.widget.RecyclerView

            android:id="@+id/active_chats"
            android:layout_width="match_parent"
            android:layout_height="510dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="2dp"
            android:layout_marginTop="57dp">

        </android.support.v7.widget.RecyclerView>

        <include
            android:id="@+id/include2"
            layout="@layout/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            />

    </RelativeLayout>
</code>```

My Adapter:

```<code>public class ActiveChatConvo extends RecyclerView.Adapter<ActiveChatConvo.ViewHolder>
{
    private ArrayList<User> mUsers;
    private Context mContext;

    public ActiveChatConvo(ArrayList<User> photos,Context dick) {
        mUsers = photos;
        mContext = dick;
    }

    private Context getContext() {
        return mContext;
    }

    @Override
    public ActiveChatConvo.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);

        // Inflate the custom layout
        View contactView = inflater.inflate(R.layout.chat_single_item, parent, false);

        // Return a new holder instance
        ViewHolder viewHolder = new ViewHolder(contactView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        // Get the data model based on position
        User user = mUsers.get(position);

        // Set item views based on your views and data model
        TextView name = holder.mItemName;
        name.setText(user.getName());
        TextView description = holder.mItemDescription;
        description.setText(user.getEmail());
        ImageView pic = holder.mItemImage;
        Picasso.with(pic.getContext()).load(Uri.parse(user.getPic())).into(pic);

    }

    @Override
    public int getItemCount() {
        return mUsers.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private ImageView mItemImage;
        private TextView mItemName;
        private TextView mItemDescription;
        private LinearLayout layout;
        final LinearLayout.LayoutParams params;

        public ViewHolder(View v) {
            super(v);

            mItemImage = (ImageView) v.findViewById(R.id.chat_persion_image);
            mItemName = (TextView) v.findViewById(R.id.chat_persion_name);
            mItemDescription = (TextView) v.findViewById(R.id.chat_persion_email);
            layout = (LinearLayout) itemView.findViewById(R.id.show_chat_single_item_layout);
            params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            v.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            Context context = itemView.getContext();
            Intent showChatIntent = new Intent(context, ChatConversationActivity.class);
            //showPhotoIntent.putExtra(PHOTO_KEY, mPhoto);
            context.startActivity(showChatIntent);
        }
    }
}
</code>```

My main class

```<code>public class ConnectionsActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private ViewPager mViewPager;
    private TextView person_name,person_email;
    private RecyclerView recyclerView;
    private DatabaseReference mRef;
    private LinearLayoutManager mLinearLayoutManager;
    private ArrayList<User> users;
    private FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_connections);

        //Database
        mRef = FirebaseDatabase.getInstance().getReference("Users");
        mRef.keepSynced(true);

        mAuth = FirebaseAuth.getInstance();
        FirebaseUser user = mAuth.getCurrentUser();

        users = new ArrayList<>();

        mRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists())
                {

                    for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
                        String name = postSnapshot.child("Name").getValue(String.class);
                        String email = postSnapshot.child("Email").getValue(String.class);
                        String pic = postSnapshot.child("image").getValue(String.class);

                        users.add(new User(name,email,pic));
                    }
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        //Recycler View
        recyclerView = (RecyclerView)findViewById(R.id.active_chats);
        ActiveChatConvo adapter = new ActiveChatConvo(users,this);
        recyclerView.setAdapter(adapter);
        mLinearLayoutManager = new LinearLayoutManager(this);
        //mLinearLayoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(mLinearLayoutManager);

        //VIEWS

        toolbar = (Toolbar) findViewById(R.id.tToolbar);
        if (toolbar != null)
            setSupportActionBar(toolbar);

        ImageView profileActivity = (ImageView) toolbar.findViewById(R.id.action_profile);
        ImageView homeActivity = (ImageView) toolbar.findViewById(R.id.action_home);

        profileActivity.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent profileActivity = new Intent(ConnectionsActivity.this, ProfileActivity.class);
                startActivity(profileActivity);
                finish();
                overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
            }

        });

        homeActivity.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent home = new Intent(ConnectionsActivity.this, HomeActivity.class);
                startActivity(home);
                finish();
                overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
            }

        });
    }

    }
</code>```

So if the recyclerView Activity is the first activity I visit then it will not create the items.

答: Firebase is synchronize so it doesn't block the main thread of your application, that mean that your application continue executing, you need to notify the adapter after firebase finishing his job by using adapter.notifiyDatasetChanged() after the for loop

Body:
Everytime we open the activity that bares the recycler adapter it fails to load on the first try. Exiting the activity and re-entering fixes the problem. Here is a gif for example. https://gyazo.com/32dc664dd427ef1129704a09861a3708

The Item i am spawning in:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:card_view="http://schemas.android.com/tools"
    android:id="@+id/show_chat_single_item_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="70dp"

        app:cardBackgroundColor="#dcdada"
        app:cardCornerRadius="0dp"
        app:contentPadding="3dp"
        card_view:cardCornerRadius="5dp"
        card_view:cardElevation="2dp"
        card_view:cardUseCompatPadding="true">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <ImageView
                android:id="@+id/chat_persion_image"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginTop="8dp"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:srcCompat="@mipmap/ic_launcher" />

            <TextView
                android:id="@+id/chat_persion_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="0dp"
                android:text="Name"
                android:textSize="18sp"
                android:textStyle="bold"
                app:layout_constraintLeft_toRightOf="@+id/chat_persion_image"
                app:layout_constraintTop_toTopOf="@+id/chat_persion_image" />

            <TextView
                android:id="@+id/chat_persion_email"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="0dp"
                android:layout_marginTop="8dp"
                android:text="Email"
                app:layout_constraintLeft_toLeftOf="@+id/chat_persion_name"
                app:layout_constraintTop_toBottomOf="@+id/chat_persion_name" />
        </android.support.constraint.ConstraintLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>

My conversation layout:

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/msgs_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        app:theme="@style/AppTheme2"

        >

        <android.support.v7.widget.RecyclerView

            android:id="@+id/active_chats"
            android:layout_width="match_parent"
            android:layout_height="510dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginLeft="2dp"
            android:layout_marginRight="2dp"
            android:layout_marginTop="57dp">

        </android.support.v7.widget.RecyclerView>

        <include
            android:id="@+id/include2"
            layout="@layout/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            />

    </RelativeLayout>

My Adapter:

public class ActiveChatConvo extends RecyclerView.Adapter<ActiveChatConvo.ViewHolder>
{
    private ArrayList<User> mUsers;
    private Context mContext;

    public ActiveChatConvo(ArrayList<User> photos,Context dick) {
        mUsers = photos;
        mContext = dick;
    }

    private Context getContext() {
        return mContext;
    }

    @Override
    public ActiveChatConvo.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        Context context = parent.getContext();
        LayoutInflater inflater = LayoutInflater.from(context);

        // Inflate the custom layout
        View contactView = inflater.inflate(R.layout.chat_single_item, parent, false);

        // Return a new holder instance
        ViewHolder viewHolder = new ViewHolder(contactView);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        // Get the data model based on position
        User user = mUsers.get(position);

        // Set item views based on your views and data model
        TextView name = holder.mItemName;
        name.setText(user.getName());
        TextView description = holder.mItemDescription;
        description.setText(user.getEmail());
        ImageView pic = holder.mItemImage;
        Picasso.with(pic.getContext()).load(Uri.parse(user.getPic())).into(pic);

    }

    @Override
    public int getItemCount() {
        return mUsers.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        private ImageView mItemImage;
        private TextView mItemName;
        private TextView mItemDescription;
        private LinearLayout layout;
        final LinearLayout.LayoutParams params;

        public ViewHolder(View v) {
            super(v);

            mItemImage = (ImageView) v.findViewById(R.id.chat_persion_image);
            mItemName = (TextView) v.findViewById(R.id.chat_persion_name);
            mItemDescription = (TextView) v.findViewById(R.id.chat_persion_email);
            layout = (LinearLayout) itemView.findViewById(R.id.show_chat_single_item_layout);
            params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            v.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            Context context = itemView.getContext();
            Intent showChatIntent = new Intent(context, ChatConversationActivity.class);
            //showPhotoIntent.putExtra(PHOTO_KEY, mPhoto);
            context.startActivity(showChatIntent);
        }
    }
}

My main class

public class ConnectionsActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private ViewPager mViewPager;
    private TextView person_name,person_email;
    private RecyclerView recyclerView;
    private DatabaseReference mRef;
    private LinearLayoutManager mLinearLayoutManager;
    private ArrayList<User> users;
    private FirebaseAuth mAuth;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_connections);

        //Database
        mRef = FirebaseDatabase.getInstance().getReference("Users");
        mRef.keepSynced(true);

        mAuth = FirebaseAuth.getInstance();
        FirebaseUser user = mAuth.getCurrentUser();

        users = new ArrayList<>();

        mRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists())
                {

                    for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
                        String name = postSnapshot.child("Name").getValue(String.class);
                        String email = postSnapshot.child("Email").getValue(String.class);
                        String pic = postSnapshot.child("image").getValue(String.class);

                        users.add(new User(name,email,pic));
                    }
                }

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        //Recycler View
        recyclerView = (RecyclerView)findViewById(R.id.active_chats);
        ActiveChatConvo adapter = new ActiveChatConvo(users,this);
        recyclerView.setAdapter(adapter);
        mLinearLayoutManager = new LinearLayoutManager(this);
        //mLinearLayoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(mLinearLayoutManager);

        //VIEWS

        toolbar = (Toolbar) findViewById(R.id.tToolbar);
        if (toolbar != null)
            setSupportActionBar(toolbar);

        ImageView profileActivity = (ImageView) toolbar.findViewById(R.id.action_profile);
        ImageView homeActivity = (ImageView) toolbar.findViewById(R.id.action_home);

        profileActivity.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent profileActivity = new Intent(ConnectionsActivity.this, ProfileActivity.class);
                startActivity(profileActivity);
                finish();
                overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
            }

        });

        homeActivity.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent home = new Intent(ConnectionsActivity.this, HomeActivity.class);
                startActivity(home);
                finish();
                overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
            }

        });
    }

    }

So if the recyclerView Activity is the first activity I visit then it will not create the items.


问:
How to bind a click event/function in innerHTML Angular 2?
I have an innerHTML as below:

```<code>getWidgetItem(widgetId: any) {
      this._widgetId = widgetId;
      this.widgets = [{'name': 'Welcome'}, {'name': 'Welcome1'}, {'name': 'Welcome2'}];
      this.newArray = this.widgets.map((obj) => {
        let htmlText = `
          <div>
            <section class="page subpage dashboard dashboard-page" style="overflow-y:hidden;">
                <div class="newDashbaord">
                  <header>
                      <div class="actions">
                          <button class="control-btn borderless close-btn">
                              <span #target class="icon-close action-icon" (click)="RemoveWidget(${obj})"></span>
                          </button>
                      </div>
                      <h1 class="table-heading">${obj.name}</h1>
                  </header>
                    <main>
                    </main>
                </div>
            </section>
          </div>`;
          return htmlText;
      });
  }
</code>```

But the problem is, I cant access the click event from my span.

I have a function call as below:

```<code>private RemoveWidget(widget:any) {
    if (typeof widget != 'undefined' && typeof this.widgets != 'undefined'){
      console.log('CALLEDe', widget);
      let index: number = this.widgets.indexOf(widget);
      if (index !== -1) {
          this.widgets.splice(index, 1);
      }
    }
  }
</code>```

I tried:

```<code>ngAfterContentInit(): void {
        // console.log('target called', this.elementRef.nativeElement.querySelector('span'));
        this.renderer.listen(this.elementRef.nativeElement, 'click', (event) => {
            console.log('event called??', event);
            // this.RemoveWidget(event);
        });
  }
</code>```

But am getting a span from my templateUrl. Cant access the span in my innerHTML span. How can I access it?

答:
You really should use angular's templating engine.

Instead of trying to add the html via script, you could achieve your desired outcome simply with the following in straight html with the use of *ngFor.

```<code>some-file.html

<div *ngFor="let widget of widgets">
  <section class="page subpage dashboard dashboard-page" style="overflow-y:hidden;">
    <div class="newDashbaord">
      <header>
        <div class="actions">
          <button class="control-btn borderless close-btn">
            <span #target class="icon-close action-icon" (click)="RemoveWidget(widget)"></span>
          </button>
        </div>
        <h1 class="table-heading">widget.name</h1>
      </header>
      <main>
      </main>
    </div>
  </section>
</div>
</code>```

The NgFor directive instantiates a template once per item from an iterable. The context for each instantiated template inherits from the outer context with the given loop variable set to the current item from the iterable.

Body:
I have an innerHTML as below:

getWidgetItem(widgetId: any) {
      this._widgetId = widgetId;
      this.widgets = [{'name': 'Welcome'}, {'name': 'Welcome1'}, {'name': 'Welcome2'}];
      this.newArray = this.widgets.map((obj) => {
        let htmlText = `

                          <button class="control-btn borderless close-btn">

                          </button>

${obj.name}

`;
          return htmlText;
      });
  }

But the problem is, I cant access the click event from my span.

I have a function call as below:

private RemoveWidget(widget:any) {
    if (typeof widget != 'undefined' && typeof this.widgets != 'undefined'){
      console.log('CALLEDe', widget);
      let index: number = this.widgets.indexOf(widget);
      if (index !== -1) {
          this.widgets.splice(index, 1);
      }
    }
  }

I tried:

ngAfterContentInit(): void {
        // console.log('target called', this.elementRef.nativeElement.querySelector('span'));
        this.renderer.listen(this.elementRef.nativeElement, 'click', (event) => {
            console.log('event called??', event);
            // this.RemoveWidget(event);
        });
  }

But am getting a span from my templateUrl. Cant access the span in my innerHTML span. How can I access it?

Body:
You really should use angular's templating engine.

Instead of trying to add the html via script, you could achieve your desired outcome simply with the following in straight html with the use of *ngFor.

some-file.html

<div *ngFor="let widget of widgets">
  <section class="page subpage dashboard dashboard-page" style="overflow-y:hidden;">
    <div class="newDashbaord">
      <header>
        <div class="actions">
          <button class="control-btn borderless close-btn">
            <span #target class="icon-close action-icon" (click)="RemoveWidget(widget)"></span>
          </button>
        </div>
        <h1 class="table-heading">widget.name</h1>
      </header>
      <main>
      </main>
    </div>
  </section>
</div>

The NgFor directive instantiates a template once per item from an iterable. The context for each instantiated template inherits from the outer context with the given loop variable set to the current item from the iterable.


问:
Managing third party javascript libraries with bundled jQuery
I am working on a website globalization project, which involves (us the vendor) asking our clients to insert a script tag on their home/origin site. The script tag is necessary for helping our clients go global, and part of the solution embodies a UI that gets triggered based on certain end user criteria.

The UI is built through the help of jQuery, which we really can't expect our clients to insert on their pages, not to mention version mismatches will be hard to resolve. Therefore, our third party library downloads its own jQuery version, albeit namespaced differently to avoid any conflicts.

However, such a mechanism requires us to rename all instances of jQuery to something that will help us avoid name clashes with another jQuery instance (if present), and makes the our mangled jQuery (MY_Query in examples below) very hard to manage, let alone upgrade.

For example

```<code>jQuery = window.jQuery = window.$ = function( selector, context ) {
    // The jQuery object is actually just the init constructor 'enhanced'
    return new jQuery.fn.init( selector, context );
},
.
.
.
jQuery.fn = jQuery.prototype = ...
</code>```

becomes

```<code>MY_JQuery = window.MY_JQuery = window.MY_Q = function( selector, context ) {
    // The MY_JQuery object is actually just the init constructor 'enhanced'
    return new MY_JQuery.fn.init( selector, context );
},
.
.
.
MP_JQuery.fn = MP_JQuery.prototype = ...
</code>```

In an ideal world, both us and the client would have a single version of jQuery on the site, and we both would use it to our advantage. But that would mean an upgrade of jQuery would require heavy testing on both sides (while the mangled jQuery version is contained) and that any plugin wanted would require the client to add appropriate script tags to their site, spurring a political debate between the two parties on what versions win.

So, can I manage our jQuery version (with plugins) on a client site without having to rename all instances of jQuery with something like MY_Query with the constraints mentioned above?

答:
Why not check to see if they have jQuery already included on the page and if not dynamically load it? If you know the base level jQuery needed you can check for that like this:

```<code>if( !jQuery || !jQuery.fn.jquery === "1.4.4"){
  var url = "http://code.jquery.com/jquery-1.4.4.js";
  var script = document.createElement( 'script' );
  script.type = 'text/javascript';
  script.src = url;
  document.body.appendChild(script);
}
</code>```

You'd probably want to improve the version detection to make sure that it doesn't have a version after 1.4.4, but I'm sure you could write the code for that yourself ;-)

==== Edit based on feedback

So you need to maintain multiple versions of jquery on the page. Have you tried something like this:

```<code>var original_jquery = $().noConflict();
original_jquery.getScript("http://code.jquery.com/jquery-1.4.4.js");
var new_jquery = $().noConflict();
window.$ = original_jquery;
</code>```

Then use the new_jquery as your version of jquery? I haven't tested this to see if it would work, but you might have some luck with it.

==== Final edit

As you mentioned, my javascript above wasn't exactly correct, so I tried out a few things in the console. And yes, you don't need to save the old version of jQuery because jQuery does that in the noConflict method. So just call getScript, then noConflict but saving to a new variable:

```<code>>> $.fn.jquery
"1.4.2"
>> $.getScript("http://code.jquery.com/jquery-1.4.4.js");
undefined
>> $.fn.jquery
"1.4.4"
>> var new_jquery = $.noConflict();
undefined
>> new_jquery.fn.jquery
"1.4.4"
>> $.fn.jquery
"1.4.2"
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am working on a website globalization project, which involves (us the vendor) asking our clients to insert a script tag on their home/origin site. The script tag is necessary for helping our clients go global, and part of the solution embodies a UI that gets triggered based on certain end user criteria.

The UI is built through the help of jQuery, which we really can't expect our clients to insert on their pages, not to mention version mismatches will be hard to resolve. Therefore, our third party library downloads its own jQuery version, albeit namespaced differently to avoid any conflicts.

However, such a mechanism requires us to rename all instances of jQuery to something that will help us avoid name clashes with another jQuery instance (if present), and makes the our mangled jQuery (MY_Query in examples below) very hard to manage, let alone upgrade.

For example

jQuery = window.jQuery = window.$ = function( selector, context ) {
    // The jQuery object is actually just the init constructor 'enhanced'
    return new jQuery.fn.init( selector, context );
},
.
.
.
jQuery.fn = jQuery.prototype = ...

becomes

MY_JQuery = window.MY_JQuery = window.MY_Q = function( selector, context ) {
    // The MY_JQuery object is actually just the init constructor 'enhanced'
    return new MY_JQuery.fn.init( selector, context );
},
.
.
.
MP_JQuery.fn = MP_JQuery.prototype = ...

In an ideal world, both us and the client would have a single version of jQuery on the site, and we both would use it to our advantage. But that would mean an upgrade of jQuery would require heavy testing on both sides (while the mangled jQuery version is contained) and that any plugin wanted would require the client to add appropriate script tags to their site, spurring a political debate between the two parties on what versions win.

So, can I manage our jQuery version (with plugins) on a client site without having to rename all instances of jQuery with something like MY_Query with the constraints mentioned above?

Body:
Why not check to see if they have jQuery already included on the page and if not dynamically load it? If you know the base level jQuery needed you can check for that like this:

if( !jQuery || !jQuery.fn.jquery === "1.4.4"){
  var url = "http://code.jquery.com/jquery-1.4.4.js";
  var script = document.createElement( 'script' );
  script.type = 'text/javascript';
  script.src = url;
  document.body.appendChild(script);
}

You'd probably want to improve the version detection to make sure that it doesn't have a version after 1.4.4, but I'm sure you could write the code for that yourself ;-)

==== Edit based on feedback

So you need to maintain multiple versions of jquery on the page. Have you tried something like this:

var original_jquery = $().noConflict();
original_jquery.getScript("http://code.jquery.com/jquery-1.4.4.js");
var new_jquery = $().noConflict();
window.$ = original_jquery;

Then use the new_jquery as your version of jquery? I haven't tested this to see if it would work, but you might have some luck with it.

==== Final edit

As you mentioned, my javascript above wasn't exactly correct, so I tried out a few things in the console. And yes, you don't need to save the old version of jQuery because jQuery does that in the noConflict method. So just call getScript, then noConflict but saving to a new variable:

>> $.fn.jquery
"1.4.2"
>> $.getScript("http://code.jquery.com/jquery-1.4.4.js");
undefined
>> $.fn.jquery
"1.4.4"
>> var new_jquery = $.noConflict();
undefined
>> new_jquery.fn.jquery
"1.4.4"
>> $.fn.jquery
"1.4.2"


问:
Select all rows from table in Yii
I want get all rows of ref table : ciudad

```<code>public function actionGetCiudades(){
    $model = ciudad::model()->findAll();
    $lCiudades = array();
    $i=0;

    $dataReader = Yii::app()->db->createCommand( 'SELECT * FROM ciudad' )->query();
    foreach( $dataReader as $row ) {
        $ciudad = new ciudad;
        echo $row->ciudadid.":".$row->estadoid.":".$row->ciudaddsc.":".$row->activo;
        echo "<br/";
        unset( $ciudad );

    }
</code>```

Unfortunately, output is :

```<code>:::
</code>```

But I have 700+ rows in my table.

What's wrong???

UPDATE :

var_dump($dataReader) -->

```<code> array(4) { ["ciudadid"]=> string(1) "1" ["estadoid"]=> string(1) "1" ["ciudaddsc"]=> string(15) "VALLE DE MEXICO" ["activo"]=> string(1) "1" } [1]=> array(4) { ["ciudadid"]=> string(1) "2" ["estadoid"]=> string(1) "1" ["ciudaddsc"]=> string(6) "TOLUCA" ["activo"]=> string(1) "1" } [2]=> array(4) { ["ciudadid"]=> string(1) "3" ["estadoid"]=> string(1) "1" ["ciudaddsc"]=> string(11) "ATLACOMULCO" ["activo"]=> string(1) "1" } [3]=> array(4) { ["ciudadid"]=> string(1) "4" ["estadoid"]=> string(1) "2" ["ciudaddsc"]=> string(14) "AGUASCALIENTES" ["activo"]=> string(1) "1" } [4]=> array(4) { ["ciudadid"]=> string(1) "5" ["estadoid"]=> string(1) "2" ["ciudaddsc"]=> string(18) "SAN JOSE DE GRACIA" ["activo"]=> string(1) "1" } [5]=> array(4) { ["ciudadid"]=> string(1) "6" ["estadoid"]=> string(1) "2" ["ciudaddsc"]=> string(19) "PABELLON DE ARTEAGA" ["activo"]=> string(1) "1" } [6]=> array(4) { ["ciudadid"]=> string(1) "7" ["estadoid"]=> string(1) "2" ["ciudaddsc"]=> string(8) "CALVILLO" ["activo"]=> string(1) "1" } [7]=> array(4) { ["ciudadid"]=> string(1) "8" ["estadoid"]=> string(1) "2" ["ciudaddsc"]=> string(19) "ENCARNACION DE DIAZ" ["activo"]=> string(1) "1" } [8]=> array(4) { ["ciudadid"]=> string(1) "9" ["estadoid"]=> string(1) "2" ["ciudaddsc"]=> string(15) "RINCON DE ROMOS" ["activo"]=> string(1) "1" } [9]=> array(4) { ["ciudadid"]=> string(2) "10" ["estadoid"]=> string(1) "3" ["ciudaddsc"]=> string(8) "ENSENADA" ["activo"]=> string(1) "1" } [10]=> array(4) { ["ciudadid"]=> string(2) "11" ["estadoid"]=> string(1) "3" ["ciudaddsc"]=> string(7) "TIJUANA" ["activo"]=> string(1) "1" } [11]=> array(4) { ["ciudadid"]=> string(2) "12" ["estadoid"]=> string(1) "3" ["ciudaddsc"]=> string(8) "MEXICALI" ["activo"]=> string(1) "1" } [12]=> array(4) { ["ciudadid"]=> string(2) "13" ["estadoid"]=> string(1) "3" ["ciudaddsc"]=> string(8) "ROSARITO" ["activo"]=> string(1) "1" } [13]=> array(4) { ["ciudadid"]=> string(2) "14" ["estadoid"]=> string(1) "3" ["ciudaddsc"]=> string(6) "TECATE" ["activo"]=> string(1) "1" } [14]=> array(4) { ["ciudadid"]=> string(2) "15" ["estadoid"]=> string(1) "3" ["ciudaddsc"]=> string(7) "LA MESA" ["activo"]=> string(1) "1" } [15]=> array(4) { ["ciudadid"]=> string(2) "16" ["estadoid"]=> string(1) "4" ["ciudaddsc"]=> string(6) "LA PAZ" ["activo"]=> string(1) "1" } [16]=> array(4) { ["ciudadid"]=> string(2) "17" ["estadoid"]=> string(1) "4" ["ciudaddsc"]=> string(9) "LOS CABOS" ["activo"]=> string(1) "1" } [17]=> array(4) { ["ciudadid"]=> string(2) "18" ["estadoid"]=> string(1) "4" ["ciudaddsc"]=> string(7) "COMONDU" ["activo"]=> string(1) "1" } [18]=> array(4) { ["ciudadid"]=> string(2) "19" ["estadoid"]=> string(1) "4" ["ciudaddsc"]=> string(14) "CABOS AN LUCAS" ["activo"]=> string(1) "1" } [19]=> array(4) { ["ciudadid"]=> string(2) "20" ["estadoid"]=> string(1) "4" ["ciudaddsc"]=> string(17) "SAN JOSE DEL CABO" ["activo"]=> string(1) "1" } [20]=> array(4) { ["ciudadid"]=> string(2) "21" ["estadoid"]=> string(1) "4" ["ciudaddsc"]=> string(19) "CIUDAD CONSTITUCION" ["activo"]=> string(1) "1" } [21]=> array(4) { ["ciudadid"]=> string(2) "22" ["estadoid"]=> string(1) "5" ["ciudaddsc"]=> string(8) "CAMPECHE" ["activo"]=> string(1) "1" } [22]=> array(4) { ["ciudadid"]=> string(2) "23" ["estadoid"]=> string(1) "5" ["ciudaddsc"]=> string(17) "CIUDAD DEL CARMEN" ["activo"]=> string(1) "1" } [23]=> array(4) { ["ciudadid"]=> string(2) "24" ["estadoid"]=> string(1) "5" ["ciudaddsc"]=> string(9) "ESCARCEGA" ["activo"]=> string(1) "1" } [24]=> array(4) { ["ciudadid"]=> string(2) "25" ["estadoid"]=> string(1) "5" ["ciudaddsc"]=> string(7) "CALAKUL" ["activo"]=> string(1) "1" } [25]=> array(4) { ["ciudadid"]=> string(2) "26" ["estadoid"]=> string(1) "5" ["ciudaddsc"]=> string(7) "CALKINI" ["activo"]=> string(1) "1" }
</code>```

答:
As the Question title is generic let me post a generic answer to the question.

i am using Yii 2.

to get All rows from a table without applying any where class here is how you will get.

```<code>$dbusers = New Users;
$users = $dbusers->find()->all();
</code>```

Your model should look like this.

```<code>namespace app\models;

use Yii;
use yii\db\ActiveRecord;

class Users extends ActiveRecord
{

    public function rules()
    {
        return [
            [['name', 'id','email','type'], 'required'],
            ['id', 'numeric'],
        ];
    }
}
</code>```

Title: Select all rows from table in Yii

Body:
I want get all rows of ref table : ciudad

public function actionGetCiudades(){
    $model = ciudad::model()->findAll();
    $lCiudades = array();
    $i=0;

    $dataReader = Yii::app()->db->createCommand( 'SELECT * FROM ciudad' )->query();
    foreach( $dataReader as $row ) {
        $ciudad = new ciudad;
        echo $row->ciudadid.":".$row->estadoid.":".$row->ciudaddsc.":".$row->activo;
        echo "<br/";
        unset( $ciudad );

    }

Unfortunately, output is :

:::

But I have 700+ rows in my table.

What's wrong???

UPDATE :

var_dump($dataReader) -->

 array(4) { ["ciudadid"]=> string(1) "1" ["estadoid"]=> string(1) "1" ["ciudaddsc"]=> string(15) "VALLE DE MEXICO" ["activo"]=> string(1) "1" } [1]=> array(4) { ["ciudadid"]=> string(1) "2" ["estadoid"]=> string(1) "1" ["ciudaddsc"]=> string(6) "TOLUCA" ["activo"]=> string(1) "1" } [2]=> array(4) { ["ciudadid"]=> string(1) "3" ["estadoid"]=> string(1) "1" ["ciudaddsc"]=> string(11) "ATLACOMULCO" ["activo"]=> string(1) "1" } [3]=> array(4) { ["ciudadid"]=> string(1) "4" ["estadoid"]=> string(1) "2" ["ciudaddsc"]=> string(14) "AGUASCALIENTES" ["activo"]=> string(1) "1" } [4]=> array(4) { ["ciudadid"]=> string(1) "5" ["estadoid"]=> string(1) "2" ["ciudaddsc"]=> string(18) "SAN JOSE DE GRACIA" ["activo"]=> string(1) "1" } [5]=> array(4) { ["ciudadid"]=> string(1) "6" ["estadoid"]=> string(1) "2" ["ciudaddsc"]=> string(19) "PABELLON DE ARTEAGA" ["activo"]=> string(1) "1" } [6]=> array(4) { ["ciudadid"]=> string(1) "7" ["estadoid"]=> string(1) "2" ["ciudaddsc"]=> string(8) "CALVILLO" ["activo"]=> string(1) "1" } [7]=> array(4) { ["ciudadid"]=> string(1) "8" ["estadoid"]=> string(1) "2" ["ciudaddsc"]=> string(19) "ENCARNACION DE DIAZ" ["activo"]=> string(1) "1" } [8]=> array(4) { ["ciudadid"]=> string(1) "9" ["estadoid"]=> string(1) "2" ["ciudaddsc"]=> string(15) "RINCON DE ROMOS" ["activo"]=> string(1) "1" } [9]=> array(4) { ["ciudadid"]=> string(2) "10" ["estadoid"]=> string(1) "3" ["ciudaddsc"]=> string(8) "ENSENADA" ["activo"]=> string(1) "1" } [10]=> array(4) { ["ciudadid"]=> string(2) "11" ["estadoid"]=> string(1) "3" ["ciudaddsc"]=> string(7) "TIJUANA" ["activo"]=> string(1) "1" } [11]=> array(4) { ["ciudadid"]=> string(2) "12" ["estadoid"]=> string(1) "3" ["ciudaddsc"]=> string(8) "MEXICALI" ["activo"]=> string(1) "1" } [12]=> array(4) { ["ciudadid"]=> string(2) "13" ["estadoid"]=> string(1) "3" ["ciudaddsc"]=> string(8) "ROSARITO" ["activo"]=> string(1) "1" } [13]=> array(4) { ["ciudadid"]=> string(2) "14" ["estadoid"]=> string(1) "3" ["ciudaddsc"]=> string(6) "TECATE" ["activo"]=> string(1) "1" } [14]=> array(4) { ["ciudadid"]=> string(2) "15" ["estadoid"]=> string(1) "3" ["ciudaddsc"]=> string(7) "LA MESA" ["activo"]=> string(1) "1" } [15]=> array(4) { ["ciudadid"]=> string(2) "16" ["estadoid"]=> string(1) "4" ["ciudaddsc"]=> string(6) "LA PAZ" ["activo"]=> string(1) "1" } [16]=> array(4) { ["ciudadid"]=> string(2) "17" ["estadoid"]=> string(1) "4" ["ciudaddsc"]=> string(9) "LOS CABOS" ["activo"]=> string(1) "1" } [17]=> array(4) { ["ciudadid"]=> string(2) "18" ["estadoid"]=> string(1) "4" ["ciudaddsc"]=> string(7) "COMONDU" ["activo"]=> string(1) "1" } [18]=> array(4) { ["ciudadid"]=> string(2) "19" ["estadoid"]=> string(1) "4" ["ciudaddsc"]=> string(14) "CABOS AN LUCAS" ["activo"]=> string(1) "1" } [19]=> array(4) { ["ciudadid"]=> string(2) "20" ["estadoid"]=> string(1) "4" ["ciudaddsc"]=> string(17) "SAN JOSE DEL CABO" ["activo"]=> string(1) "1" } [20]=> array(4) { ["ciudadid"]=> string(2) "21" ["estadoid"]=> string(1) "4" ["ciudaddsc"]=> string(19) "CIUDAD CONSTITUCION" ["activo"]=> string(1) "1" } [21]=> array(4) { ["ciudadid"]=> string(2) "22" ["estadoid"]=> string(1) "5" ["ciudaddsc"]=> string(8) "CAMPECHE" ["activo"]=> string(1) "1" } [22]=> array(4) { ["ciudadid"]=> string(2) "23" ["estadoid"]=> string(1) "5" ["ciudaddsc"]=> string(17) "CIUDAD DEL CARMEN" ["activo"]=> string(1) "1" } [23]=> array(4) { ["ciudadid"]=> string(2) "24" ["estadoid"]=> string(1) "5" ["ciudaddsc"]=> string(9) "ESCARCEGA" ["activo"]=> string(1) "1" } [24]=> array(4) { ["ciudadid"]=> string(2) "25" ["estadoid"]=> string(1) "5" ["ciudaddsc"]=> string(7) "CALAKUL" ["activo"]=> string(1) "1" } [25]=> array(4) { ["ciudadid"]=> string(2) "26" ["estadoid"]=> string(1) "5" ["ciudaddsc"]=> string(7) "CALKINI" ["activo"]=> string(1) "1" }

Body:
As the Question title is generic let me post a generic answer to the question.

i am using Yii 2.

to get All rows from a table without applying any where class here is how you will get.

$dbusers = New Users;
$users = $dbusers->find()->all();

Your model should look like this.

namespace app\models;

use Yii;
use yii\db\ActiveRecord;

class Users extends ActiveRecord
{

    public function rules()
    {
        return [
            [['name', 'id','email','type'], 'required'],
            ['id', 'numeric'],
        ];
    }
}

ContentLicense: CC BY-SA 4.0


问:
Maximum path sum In a triangle with prime number check
I was given this algorithm task:

You will have a triangle input below and you need to find the maximum sum of the numbers according to given rules below;

You will start from the top and move downwards to an adjacent number as in below.

You are only allowed to walk downwards and diagonally.

You can only walk over NON PRIME NUMBERS.

```<code>     1
    8 4
  2  6  9
 8  5  9  3
</code>```

As you can see this has several paths that fits the rule of NOT PRIME NUMBERS; 1>8>6>9, 1>4>6>9, 1>4>9>9
1 + 8 + 6 + 9 = 24.  As you see 1, 8, 6, 9 are all NOT PRIME NUMBERS and walking over these yields the maximum sum.

According to above rules what is the maximum sum of below input? It means please take this pyramid as an input (as file or constants directly inside the code) for your implementation and solve by using it.

```<code>                                  215
                               193 124
                             117 237 442
                           218 935 347 235
                         320 804 522 417 345
                       229 601 723 835 133 124
                     248 202 277 433 207 263 257
                   359 464 504 528 516 716 871 182
                 461 441 426 656 863 560 380 171 923
               381 348 573 533 447 632 387 176 975 449
             223 711 445 645 245 543 931 532 937 541 444
           330 131 333 928 377 733 017 778 839 168 197 197
        131 171 522 137 217 224 291 413 528 520 227 229 928
      223 626 034 683 839 053 627 310 713 999 629 817 410 121
    924 622 911 233 325 139 721 218 253 223 107 233 230 124 233
</code>```

Note that, each node has only two children here (except the most bottom ones). As an example, you can walk from 215 to 124 (because 193 is a prime) then from 124 to either 237 or 442. From 124 you cannot go to 117 because it’s not a direct child of 124.

I know there are different approaches of solving this problem which can be

Brute Force method

Dynamic Programming method

I used Dynamic Programming method approach due to its efficiency:

```<code>using System;

class Program
{
    static void Main(string[] args)
    {

        //get input
        var input = GetInput();

        string[] arrayOfRowsByNewlines = input.Split('\n');

        var tableHolder = FlattenTheTriangleIntoTable(arrayOfRowsByNewlines);

        var result = WalkThroughTheNode(arrayOfRowsByNewlines, tableHolder);

        Console.WriteLine($"The Maximum Total Sum Of Non-Prime Numbers From Top To Bottom Is:  {result[0,0]}");

        Console.ReadKey();
    }

    private static string GetInput()
    {

            const string input = @"   215
                                   193 124
                                  117 237 442
                                218 935 347 235
                              320 804 522 417 345
                            229 601 723 835 133 124
                          248 202 277 433 207 263 257
                        359 464 504 528 516 716 871 182
                      461 441 426 656 863 560 380 171 923
                     381 348 573 533 447 632 387 176 975 449
                   223 711 445 645 245 543 931 532 937 541 444
                 330 131 333 928 377 733 017 778 839 168 197 197
                131 171 522 137 217 224 291 413 528 520 227 229 928
              223 626 034 683 839 053 627 310 713 999 629 817 410 121
            924 622 911 233 325 139 721 218 253 223 107 233 230 124 233";
        return input;
    }

    private static int[,] WalkThroughTheNode(string[] arrayOfRowsByNewlines, int[,] tableHolder)
    {
        // walking through the non-prime node
        for (int i = arrayOfRowsByNewlines.Length - 2; i >= 0; i--)
        {
            for (int j = 0; j < arrayOfRowsByNewlines.Length; j++)
            {
                //only sum through the non-prime node
                if ((!IsPrime(tableHolder[i, j])))
                {
                    tableHolder[i, j] = Math.Max(tableHolder[i, j] + tableHolder[i + 1, j],
                        tableHolder[i, j] + tableHolder[i + 1, j + 1]);
                }
            }
        }
        return tableHolder;
    }

    private static int[,] FlattenTheTriangleIntoTable(string[] arrayOfRowsByNewlines)
    {
        int[,] tableHolder = new int[arrayOfRowsByNewlines.Length, arrayOfRowsByNewlines.Length + 1];

        for (int row = 0; row < arrayOfRowsByNewlines.Length; row++)
        {
            var eachCharactersInRow = arrayOfRowsByNewlines[row].Trim().Split(' ');

            for (int column = 0; column < eachCharactersInRow.Length; column++)
            {
                int number;
                int.TryParse(eachCharactersInRow[column], out number);
                tableHolder[row, column] = number;
            }
        }
        return tableHolder;
    }

    public static bool IsPrime(int number)
    {
        // Test whether the parameter is a prime number.
        if ((number & 1) == 0)
        {
            if (number == 2)
            {
                return true;
            }
            return false;
        }

        for (int i = 3; (i * i) <= number; i += 2)
        {
            if ((number % i) == 0)
            {
                return false;
            }
        }
        return number != 1;
    }

}
</code>```

Can somebody help me go through the code and see if there is a better way of solving it.

答:
Don't you think it is not checking the prime number check in the last row and taking max value ?

the code should be look like below:

```<code>for (int lenIndex = data.length - 1; lenIndex > 0; lenIndex--) {
        for (int i = 0; i < data[lenIndex].length - 1; i++) {
            System.out.println("---------------------");
            System.out.println("lenIndex is : " + lenIndex);
            if (!isPrimeNum(data[lenIndex - 1][i]) || (lenIndex == 1)) {
                if (lenIndex == data.length - 1) {
                    data[lenIndex - 1][i] += Math.max(isPrimeNum(data[lenIndex][i]) ? 0 : data[lenIndex][i],
                            isPrimeNum(data[lenIndex][i + 1]) ? 0 : data[lenIndex][i + 1]);

                    System.out.println("data[lenIndex][i] : " + data[lenIndex][i]+ " data[lenIndex][i + 1] :"+ data[lenIndex][i + 1]);
                    System.out.println("Number select for Sum #" + Math.max(isPrimeNum(data[lenIndex][i]) ? 0 : data[lenIndex][i],
                            isPrimeNum(data[lenIndex][i + 1]) ? 0 : data[lenIndex][i + 1]));
                } else {
                    data[lenIndex - 1][i] += Math.max(data[lenIndex][i], data[lenIndex][i + 1]);
                    System.out.println("data[lenIndex][i] : " + data[lenIndex][i]+ " data[lenIndex][i + 1] :"+ data[lenIndex][i + 1]);
                    System.out.println("Number select for Sum #" + Math.max(data[lenIndex][i], data[lenIndex][i + 1]));
                }
                System.out.println("Afrer Sum #" + data[lenIndex - 1][i]);
            } else {
                System.out.println("Prime Number - Skiping : " + data[lenIndex - 1][i]);
                data[lenIndex - 1][i] = 0;
            }
        }
</code>```

Body:
I was given this algorithm task:

You will have a triangle input below and you need to find the maximum sum of the numbers according to given rules below;

You will start from the top and move downwards to an adjacent number as in below.

You are only allowed to walk downwards and diagonally.

You can only walk over NON PRIME NUMBERS.

     1
    8 4
  2  6  9
 8  5  9  3

As you can see this has several paths that fits the rule of NOT PRIME NUMBERS; 1>8>6>9, 1>4>6>9, 1>4>9>9
1 + 8 + 6 + 9 = 24.  As you see 1, 8, 6, 9 are all NOT PRIME NUMBERS and walking over these yields the maximum sum.

According to above rules what is the maximum sum of below input? It means please take this pyramid as an input (as file or constants directly inside the code) for your implementation and solve by using it.

                                  215
                               193 124
                             117 237 442
                           218 935 347 235
                         320 804 522 417 345
                       229 601 723 835 133 124
                     248 202 277 433 207 263 257
                   359 464 504 528 516 716 871 182
                 461 441 426 656 863 560 380 171 923
               381 348 573 533 447 632 387 176 975 449
             223 711 445 645 245 543 931 532 937 541 444
           330 131 333 928 377 733 017 778 839 168 197 197
        131 171 522 137 217 224 291 413 528 520 227 229 928
      223 626 034 683 839 053 627 310 713 999 629 817 410 121
    924 622 911 233 325 139 721 218 253 223 107 233 230 124 233

Note that, each node has only two children here (except the most bottom ones). As an example, you can walk from 215 to 124 (because 193 is a prime) then from 124 to either 237 or 442. From 124 you cannot go to 117 because it’s not a direct child of 124.

I know there are different approaches of solving this problem which can be

Brute Force method

Dynamic Programming method

I used Dynamic Programming method approach due to its efficiency:

using System;

class Program
{
    static void Main(string[] args)
    {

        //get input
        var input = GetInput();

        string[] arrayOfRowsByNewlines = input.Split('\n');

        var tableHolder = FlattenTheTriangleIntoTable(arrayOfRowsByNewlines);

        var result = WalkThroughTheNode(arrayOfRowsByNewlines, tableHolder);

        Console.WriteLine($"The Maximum Total Sum Of Non-Prime Numbers From Top To Bottom Is:  {result[0,0]}");

        Console.ReadKey();
    }

    private static string GetInput()
    {

            const string input = @"   215
                                   193 124
                                  117 237 442
                                218 935 347 235
                              320 804 522 417 345
                            229 601 723 835 133 124
                          248 202 277 433 207 263 257
                        359 464 504 528 516 716 871 182
                      461 441 426 656 863 560 380 171 923
                     381 348 573 533 447 632 387 176 975 449
                   223 711 445 645 245 543 931 532 937 541 444
                 330 131 333 928 377 733 017 778 839 168 197 197
                131 171 522 137 217 224 291 413 528 520 227 229 928
              223 626 034 683 839 053 627 310 713 999 629 817 410 121
            924 622 911 233 325 139 721 218 253 223 107 233 230 124 233";
        return input;
    }

    private static int[,] WalkThroughTheNode(string[] arrayOfRowsByNewlines, int[,] tableHolder)
    {
        // walking through the non-prime node
        for (int i = arrayOfRowsByNewlines.Length - 2; i >= 0; i--)
        {
            for (int j = 0; j < arrayOfRowsByNewlines.Length; j++)
            {
                //only sum through the non-prime node
                if ((!IsPrime(tableHolder[i, j])))
                {
                    tableHolder[i, j] = Math.Max(tableHolder[i, j] + tableHolder[i + 1, j],
                        tableHolder[i, j] + tableHolder[i + 1, j + 1]);
                }
            }
        }
        return tableHolder;
    }

    private static int[,] FlattenTheTriangleIntoTable(string[] arrayOfRowsByNewlines)
    {
        int[,] tableHolder = new int[arrayOfRowsByNewlines.Length, arrayOfRowsByNewlines.Length + 1];

        for (int row = 0; row < arrayOfRowsByNewlines.Length; row++)
        {
            var eachCharactersInRow = arrayOfRowsByNewlines[row].Trim().Split(' ');

            for (int column = 0; column < eachCharactersInRow.Length; column++)
            {
                int number;
                int.TryParse(eachCharactersInRow[column], out number);
                tableHolder[row, column] = number;
            }
        }
        return tableHolder;
    }

    public static bool IsPrime(int number)
    {
        // Test whether the parameter is a prime number.
        if ((number & 1) == 0)
        {
            if (number == 2)
            {
                return true;
            }
            return false;
        }

        for (int i = 3; (i * i) <= number; i += 2)
        {
            if ((number % i) == 0)
            {
                return false;
            }
        }
        return number != 1;
    }

}

Can somebody help me go through the code and see if there is a better way of solving it.

Body:
Don't you think it is not checking the prime number check in the last row and taking max value ?

the code should be look like below:

for (int lenIndex = data.length - 1; lenIndex > 0; lenIndex--) {
        for (int i = 0; i < data[lenIndex].length - 1; i++) {
            System.out.println("---------------------");
            System.out.println("lenIndex is : " + lenIndex);
            if (!isPrimeNum(data[lenIndex - 1][i]) || (lenIndex == 1)) {
                if (lenIndex == data.length - 1) {
                    data[lenIndex - 1][i] += Math.max(isPrimeNum(data[lenIndex][i]) ? 0 : data[lenIndex][i],
                            isPrimeNum(data[lenIndex][i + 1]) ? 0 : data[lenIndex][i + 1]);

                    System.out.println("data[lenIndex][i] : " + data[lenIndex][i]+ " data[lenIndex][i + 1] :"+ data[lenIndex][i + 1]);
                    System.out.println("Number select for Sum #" + Math.max(isPrimeNum(data[lenIndex][i]) ? 0 : data[lenIndex][i],
                            isPrimeNum(data[lenIndex][i + 1]) ? 0 : data[lenIndex][i + 1]));
                } else {
                    data[lenIndex - 1][i] += Math.max(data[lenIndex][i], data[lenIndex][i + 1]);
                    System.out.println("data[lenIndex][i] : " + data[lenIndex][i]+ " data[lenIndex][i + 1] :"+ data[lenIndex][i + 1]);
                    System.out.println("Number select for Sum #" + Math.max(data[lenIndex][i], data[lenIndex][i + 1]));
                }
                System.out.println("Afrer Sum #" + data[lenIndex - 1][i]);
            } else {
                System.out.println("Prime Number - Skiping : " + data[lenIndex - 1][i]);
                data[lenIndex - 1][i] = 0;
            }
        }