问:
Display data from JSON in recyclerview using AsyncTaskLoader
please I am trying to post data from JSON in my recyclerview. I am using the AsyncTaskLoader but nothing just shows on the screen.
I have logged the data I need from JSON, to confirm I got the parsing right, and they show up. I have also logged the array of objects that are meant to be displayed, and they also show in the logcat, it is just the screen of my app that doesn't show any data. I am using a view pager with 2 fragments and this issue is the same for both.
Here is my FragmentActivity, I will post just one since issue is the same

```<code>public class TechNewsFragment extends Fragment {
private SwipeRefreshLayout mSwipeRefreshLayout;
private TextView mErrorMessage;
private NewsAdapter mNewsAdapter;
ArrayList<News> news;
NetworkInfo info;
//    The Loader takes in a bundle
Bundle sourceBundle = new Bundle();

private final String LOG_TAG = MainActivity.class.getSimpleName();

private static final String TECH_NEWS_QUERY_URL = "query";
private static final String TECH_NEWS_SOURCE = "techcrunch";
private static final int TECH_NEWS_LOADER = 22;

private RecyclerView mRecyclerView;

public TechNewsFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_news, container, false);
    mErrorMessage = (TextView) view.findViewById(R.id.tv_error_message);
    mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_main);
    mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefresh);

    mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));

    getActivity().getSupportLoaderManager().initLoader(TECH_NEWS_LOADER, null, new NewsDataLoader());

    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            Log.v(LOG_TAG, "Refreshing");
            restartLoader();
            mSwipeRefreshLayout.setColorSchemeResources(
                    R.color.colorPrimary,
                    R.color.colorPrimaryDark);
        }
    });

    return view;
}

private boolean isConnected(){
    ConnectivityManager cm = (ConnectivityManager) getActivity()
            .getSystemService(CONNECTIVITY_SERVICE);

    info = cm.getActiveNetworkInfo();

    return info != null && info.isConnectedOrConnecting();
}

private int anyRandomInt(Random random) {
    return random.nextInt();
}

private void restartLoader() {
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            URL techNewsUrl = TechNetworkUtils.buildUrl(TECH_NEWS_SOURCE);
            sourceBundle.putString(TECH_NEWS_QUERY_URL, techNewsUrl.toString());

            Random random = new Random();
            int uniqueId = anyRandomInt(random); //Generates a new ID for each loader call;

//                    sourceBundle.putString("query", s);]

            LoaderManager loaderManager = getActivity().getSupportLoaderManager();

            if (loaderManager.getLoader(TECH_NEWS_LOADER) == null) {
                loaderManager.initLoader(uniqueId, sourceBundle, new NewsDataLoader());
            } else {
                loaderManager.restartLoader(TECH_NEWS_LOADER, sourceBundle, new
                        NewsDataLoader());
            }
        }
    }, 5000);
    mSwipeRefreshLayout.setRefreshing(false);
    Log.v(LOG_TAG, "Finished refreshing");
}

private void showErrorScreen(){
    mErrorMessage.setVisibility(View.VISIBLE);
    mRecyclerView.setVisibility(View.INVISIBLE);
    mErrorMessage.setText(getString(R.string.internet_error));
}

`public class NewsDataLoader implements LoaderManager.LoaderCallbacks<ArrayList<News>> {
    @Override
    public Loader<ArrayList<News>> onCreateLoader(int id, final Bundle args) {
        if (isConnected()){
            mErrorMessage.setVisibility(View.INVISIBLE);
            mRecyclerView.setVisibility(View.VISIBLE);
            return new AsyncTaskLoader<ArrayList<News>>(getActivity()) {
                ArrayList<News> mNewsData;

                @Override
                protected void onStartLoading() {
                    super.onStartLoading();
                    if (mNewsData != null){
                        deliverResult(mNewsData);
                    }else{
                        forceLoad();
                        mSwipeRefreshLayout.setRefreshing(true);
                    }
                }

                @Override
                public ArrayList<News> loadInBackground() {
                    try {
                        ArrayList<News> news = TechNetworkUtils.parseJSON(TECH_NEWS_SOURCE);
                        return news;
                    } catch (IOException e) {
                        e.printStackTrace();
                        return null;
                    }
                }

                public void deliverResult(ArrayList<News> data) {
                    mNewsData = data;
                    super.deliverResult(data);
                }
            };
        }else{
            showErrorScreen();
            return null;
        }
    }

    @Override
    public void onLoadFinished(Loader<ArrayList<News>> loader, ArrayList<News> data) {
        mSwipeRefreshLayout.setRefreshing(false);
        if (null == data) {
            showErrorScreen();
        } else {
            mErrorMessage.setVisibility(View.INVISIBLE);
            mRecyclerView.setVisibility(View.VISIBLE);
            if (news != null) {
//                    news.clear();
                news.addAll(data);
                mNewsAdapter = new NewsAdapter(news);
                mRecyclerView.setAdapter(mNewsAdapter);
                mNewsAdapter.notifyDataSetChanged();
            } else {
                news = data;
            }
            Log.i(LOG_TAG + "  this is the data", data.toString());
// Array of objects shows in the log
        }
    }

    @Override
    public void onLoaderReset(Loader<ArrayList<News>> loader) {
//            loader.forceLoad();
    }

}

}`
</code>```

This is my adapter class

```<code>public class NewsAdapter extends
RecyclerView.Adapter<NewsAdapter.NewsHolder> {

//    Variable used to reference the model
private ArrayList<News> mNews = new ArrayList<>();

//    NewsHolder class that extends the ViewHolder
public static class NewsHolder extends RecyclerView.ViewHolder{
    private TextView mNewsTextView;
    private TextView mTimeStampTextView;

//   Constructor to set the views
    public NewsHolder(View itemView){
        super(itemView);
        mNewsTextView = (TextView) itemView.findViewById(R.id.news_tv);
        mTimeStampTextView = (TextView) itemView.findViewById(R.id.time_tv);
    }
}

//    Constructor to set the adapter
public NewsAdapter(ArrayList<News> news){
    mNews = news;
}

@Override
public NewsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view =
LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_view,
parent, false);
    return new NewsHolder(view);
}

@Override
public void onBindViewHolder(NewsHolder holder, int position) {
    holder.mNewsTextView.setText(mNews.get(position).getNews());
    holder.mTimeStampTextView.setText(mNews.get(position).getTime());
}

@Override
public int getItemCount() {
    return mNews.size();
}
}`
</code>```

This is class to parse JSON and handle network connectivity

```<code>public class TechNetworkUtils {

private static final String LOG_TAG = MainActivity.class.getSimpleName();

public static ArrayList<News> parseJSON(String source) throws IOException {
    URL url = buildUrl(source);
    String jsonResult = getResponseFromHttpUrl(url);

    ArrayList<News> news = new ArrayList<>();

    try{
        JSONObject jsonObject = new JSONObject(jsonResult);
        JSONArray jsonArray = jsonObject.getJSONArray("articles");

        if (jsonArray != null){
            for (int i = 0; i < jsonArray.length(); i++){
                JSONObject article = jsonArray.getJSONObject(i);
                String title = article.getString("title");
                String time = article.getString("publishedAt");
                news.add(new News(title, time));
                Log.i(LOG_TAG, title);
                Log.i(LOG_TAG, time);
            }
        }

    }catch (JSONException | NullPointerException e){
        e.printStackTrace();
        return null;
    }
    return news;
}

public static URL buildUrl(String techNewsSource){
    final String TECH_NEWS_BASE_URL = "https://newsapi.org/v1/articles";
    final String PARAM_SOURCE = "source";
    final String PARAM_SORT_BY = "sortBy";
    final String latest = "latest";
    final String PARAM_API_KEY = "apiKey";
    final String KEY = "3431d57e51a04c1d967e2eb96c99fd1a";

    Uri builtUri = Uri.parse(TECH_NEWS_BASE_URL).buildUpon()
            .appendQueryParameter(PARAM_SOURCE, techNewsSource)
            .appendQueryParameter(PARAM_SORT_BY, latest)
            .appendQueryParameter(PARAM_API_KEY, KEY)
            .build();

    Log.i(LOG_TAG, builtUri.toString());

    URL url = null;
    try{
        url = new URL(builtUri.toString());
    }catch (MalformedURLException e){
        e.printStackTrace();
    }
    return url;
}

public static String getResponseFromHttpUrl(URL url) throws IOException{
    HttpURLConnection urlConnection = null;
    String newsJsonStr = null;
    BufferedReader reader = null;

    try{
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setReadTimeout(15000);
        urlConnection.setConnectTimeout(10000);
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(false);
        urlConnection.setDoInput(true);
        urlConnection.connect();

        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();
        if(inputStream == null){
            return null;
        }

        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        while ((line = reader.readLine()) != null){
            buffer.append(line + "\n");
        }

        if (buffer.length() == 0){
            return null;
        }

        newsJsonStr = buffer.toString();

    }catch(IOException e){
        Log.e(LOG_TAG, "Error fetching data", e);
        return null;
    }finally{
        if (urlConnection != null){
            urlConnection.disconnect();
        }
        if (reader != null){
            try{
                reader.close();
            }catch (IOException e){
                Log.e(LOG_TAG, "Error closing stream", e);
            }
        }
    }
    return newsJsonStr;
}
}
</code>```

This is my pojo class

```<code>public class News {
private String mNews;
private String mTime;

public News(String news, String time){
    mNews = news;
    mTime = time;
}

public String getNews() {
    return mNews;
}

public String getTime() {
    return mTime;
}
}`
</code>```

This is my list_item_layout

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/title_frame">

    <TextView
        android:padding="16dp"
        android:layout_width="match_parent"
        android:layout_height="64dp"
        android:id="@+id/news_tv"
        tools:text="Get exciting news here"/>

</FrameLayout>
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end">

    <TextView
        android:id="@+id/time_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="8dp"
        android:paddingRight="16dp"
        tools:text="12:00pm"/>
</FrameLayout>

</LinearLayout>
</code>```

This is my log.i

```<code>  /*  06-06 21:35:25.834 1092-1092/com.ire.blogbot E/dalvikvm: Could not
 find
class 'android.graphics.drawable.RippleDrawable', referenced from method
android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
06-06 21:35:25.834 1092-1092/com.ire.blogbot W/dalvikvm: VFY: unable to
resolve instanceof 146 (Landroid/graphics/drawable/RippleDrawable;) in
Landroid/support/v7/widget/AppCompatImageHelper;
06-06 21:35:25.922 1092-1106/com.ire.blogbot I/MainActivity:
https://newsapi.org/v1/articles?source=entertainment-
weekly&sortBy=top&apiKey=3431d57e51a04c1d967e2eb96c99fd1a
06-06 21:35:25.934 1092-1107/com.ire.blogbot I/MainActivity:
https://newsapi.org/v1/articles?
source=techcrunch&sortBy=latest&apiKey=3431d57e51a04c1d967e2eb96c99fd1a
06-06 21:35:26.042 1092-1092/com.ire.blogbot W/EGL_genymotion:
eglSurfaceAttrib not implemented
06-06 21:35:26.226 376-423/system_process I/ActivityManager: Displayed
com.ire.blogbot/.activity.MainActivity: +606ms
06-06 21:35:26.270 376-449/system_process I/qtaguid: Failed write_ctrl(s 0
10021) res=-1 errno=1
06-06 21:35:26.270 376-449/system_process W/NetworkManagementSocketTagger:
setKernelCountSet(10021, 0) failed with errno -1
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: How can tech
companies treat their contractors better?
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: 2017-06-
06T21:19:28Z
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: Audi is the
first to test autonomous vehicles in New York
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: 2017-06-
06T20:58:34Z
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: Bragi’s Dash
Pro is a sophisticated and smart AirPods alternative
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: 2017-06-
06T20:05:41Z
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: As the Surface
line courts creatives, Apple pushes back with the iMac and iPad Pro
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: 2017-06-
06T20:04:19Z
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: What Silicon
Valley can learn from Lebanon’s women in tech
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: 2017-06-
06T20:00:53Z
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: Matt Mitchell
of CryptoHarlem is building an open source tool to help organizations
prepare for data breaches
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: 2017-06-
06T19:29:04Z
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: Pinterest
raises $150M at a $12.3B valuation as it makes a full press into
visual search
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: 2017-06-
06T19:27:05Z
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: Tulip, the app
platform for manufacturers, picks up $13 million from NEA
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: 2017-06-
06T18:45:34Z
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: Take a look at
these first pictures of Fisker’s $130K EMotion electric car
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: 2017-06-
06T18:27:57Z
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: iOS 11 will
help you free up storage on your iPhone through personalized suggestions
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: 2017-06-
06T18:22:33Z
06-06 21:35:27.182 1092-1092/com.ire.blogbot
I/MainActivity  this is the data: [com.ire.blogbot.model.News@536e8250,
com.ire.blogbot.model.News@536e65c0, com.ire.blogbot.model.News@536d157c,
com.ire.blogbot.model.News@536e80ec, com.ire.blogbot.model.News@536e80f8,
com.ire.blogbot.model.News@536e8104, com.ire.blogbot.model.News@536e8110,
com.ire.blogbot.model.News@536e811c, com.ire.blogbot.model.News@536e8128,
com.ire.blogbot.model.News@536e8134]
06-06 21:35:27.202 1092-1106/com.ire.blogbot I/MainActivity:
{"status":"ok","source":"entertainment-weekly","sortBy":"top","articles":
[{"author":null,"title":"The Zodiac Killer: How a first-time filmmaker
attempted to catch the serial
murderer","description":null,"url":"http://zodiactruecrime.ew.com/","urlT
oImage":null,"publishedAt":null},{"author":"Maureen Lee Lenker","title":"Sam
Smith teases return to the recording studio with
new photos","description":"","url":"http://ew.com/music/2017/06/06/sam-
smith-teases-new-
album/","urlToImage":"http://i0.wp.com/ewedit.files.wordpress.com/2017/06/g
ettyimages-521740878.jpg?
 crop=0px%2C82px%2C2700px%2C1418px&resize=1200%2C630&ssl=1","publishedAt":"2
017-06-06T21:22:08Z"},{"author":"Marisa Marcellino","title":"Highest-
grossing
Broadway shows of
all time","description":"","url":"http://ew.com/theater/2017/06/06/highest-
grossing-broadway-shows-of-all-
 time/","urlToImage":"http://i1.wp.com/ewedit.files.wordpress.com/2017/03/li
onking.jpg?
 crop=0px%2C42px%2C2700px%2C1419px&resize=1200%2C630&ssl=1","publishedAt":"2
017-06-06T19:52:02Z"},{"author":"Kyle Fowle","title":"'House of Cards'
Recap:
How Far Is Claire Willing to Go to Secure the
Presidency?","description":"With threats forming all around them, Frank and
Claire take violent action to secure their
legacy","url":"http://ew.com/recap/house-of-cards-season-5-episode-
 12/","urlToImage":"http://i0.wp.com/ewedit.files.wordpress.com/2017/06/hoc_
512_unit_01846r.jpg?
 crop=3px%2C105px%2C2699px%2C1418px&resize=1200%2C630&ssl=1","publishedAt":"
2017-06-06T19:49:12Z"},{"author":"Nivea Serrao","title":"Selena Gomez
responds
to ’13 Reasons Why’ controversy","description":"'This is happening every
day'","url":"http://ew.com/tv/2017/06/06/selena-gomez-13-reasons-why-
controversy-
 2/","urlToImage":"http://i1.wp.com/ewedit.files.wordpress.com/2017/04/13rw_
113_01153r.jpg?
 crop=0px%2C53px%2C2700px%2C1418px&resize=1200%2C630&ssl=1","publishedAt":"2
017-06-06T19:45:59Z"},{"author":"Ruth Kinane","title":"‘Hollywood Game
Night’
teaser: ‘This Is Us,’ ‘Veep,’ ‘Walking Dead’ casts ready
for battle","description":"Jane Lynch returns to
host","url":"http://ew.com/tv/2017/06/06/hollywood-game-night-teaser-this-
is-us-veep-walking-dead-
 casts/","urlToImage":"http://i1.wp.com/ewedit.files.wordpress.com/2017/06/h
ollywoodgame.jpg?
 crop=0px%2C21px%2C2700px%2C1419px&resize=1200%2C630&ssl=1","publishedAt":"2
017-06-06T19:30:49Z"},{"author":"Joey Nolfi","title":"Watch Jerry Seinfeld
refuse a hug from Kesha","description":"\"I don't know who that was... I
wish her the best,\" the 63-year-old
said","url":"http://ew.com/news/2017/06/06/jerry-seinfeld-kesha-
 hug/","urlToImage":"http://i0.wp.com/ewedit.files.wordpress.com/2017/06/sei
nfeldkesha.jpg?
 crop=0px%2C13px%2C3200px%2C1681px&resize=1200%2C630&ssl=1","publishedAt":"2
017-06-06T19:05:57Z"},{"author":"Maureen Lee Lenker","title":"Tonys 2017:
Watch
performances from this year’s Best
 Musical nominees","description":"","url":"http://ew.com/theater/2017/06/06/
tonys-2017-nominations-best-musical-
 performances/","urlToImage":"http://i2.wp.com/ewedit.files.wordpress.com/20
17/0
6/deh-ben-platt-4449-photo.jpg?
 crop=0px%2C382px%2C2700px%2C1419px&resize=1200%2C630&ssl=1","publishedAt":"
2017
-06-06T19:00:59Z"},{"author":"Ray Rahman","title":"‘Broad City’ returns
under a ‘cloud of doom,’ stars tease","description":"Plus: RuPaul makes a
'f---ing titillating' and 'godlike'
cameo","url":"http://ew.com/tv/2017/06/06/broad-city-season-4-
 winter/","urlToImage":"http://i2.wp.com/ewedit.files.wordpress.com/2017/06/
broadcity.jpg?
 crop=0px%2C87px%2C2700px%2C1419px&resize=1200%2C630&ssl=1","publishedAt":"2
017-06-06T18:56:12Z"},{"author":"Nivea Serrao","title":"How ‘The Moth’
podcast
turned storytelling into a
 worldwide movement","description":"","url":"http://ew.com/podcasts/2017/06/
06/the-moth-podcast-20th-
 anniversary/","urlToImage":"http://i1.wp.com/ewedit.files.wordpress.com/201
7/06/gettyimages-530299778.jpg?
crop=0px%2C18px%2C1800px%2C945px&resize=1200%2C630","publishedAt":"2017-
06-06T18:48:15Z"}]}
06-06 21:35:33.406 376-386/system_process I/ActivityManager: No longer want
com.android.exchange (pid 870): hidden #16
06-06 21:41:36.890 55-55/? W/Genyd: Can't parse request
06-06 21:41:36.958 376-466/system_process I/ClipboardService: Got clipboard
for user=0
06-06 21:41:36.958 376-466/system_process I/ClipboardService: Got clipboard
for user=0
06-06 21:41:36.958 376-389/system_process I/ClipboardService: Got clipboard
for user=0
06-06 21:41:36.958 376-389/system_process I/ClipboardService: Got clipboard
for user=0
06-06 21:41:36.958 376-389/system_process I/ClipboardService: Got clipboard
for user=0
06-06 21:41:37.158 376-466/system_process I/ClipboardService: Got clipboard
for user=0
06-06 21:41:37.158 376-466/system_process I/ClipboardService: Got clipboard
for user=0
06-06 21:41:37.162 376-389/system_process I/ClipboardService: Got clipboard
for user=0
06-06 21:41:37.162 376-389/system_process I/ClipboardService: Got clipboard
for user=0
06-06 21:41:37.162 376-389/system_process I/ClipboardService: Got clipboard
for user=0
</code>```

I need the data to display automatically when the app is launched and refresh when onSwipeRefreshLayout is called.

答:
I have run your project and I didn't get the error which you have posted from logcat instead I've got NullPointerException in this line of code:

String techNewsUrlString = args.getString(TECH_NEWS_QUERY_URL);

So I replaced the args with your sourceBundle and that fix the error:

String techNewsUrlString = sourceBundle.getString(TECH_NEWS_QUERY_URL);

Second issue was in your fragment_news xml code. Your TextView occupied all space and there wasn't room for Recyclerview so I made some changes:

```<code>  <?xml version="1.0" encoding="utf-8"?>
 <android.support.v4.widget.SwipeRefreshLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/swipeRefresh"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/tv_error_message"
    android:text="Oops! Couldn't connect to a network"
    android:gravity="center"
    android:layout_margin="32dp"
    android:textSize="16sp"
    android:fontFamily="monospace"
    android:visibility="invisible"/>
<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
 </RelativeLayout>
</android.support.v4.widget.SwipeRefreshLayout>
</code>```

And your project should work now.

Body:
please I am trying to post data from JSON in my recyclerview. I am using the AsyncTaskLoader but nothing just shows on the screen.
I have logged the data I need from JSON, to confirm I got the parsing right, and they show up. I have also logged the array of objects that are meant to be displayed, and they also show in the logcat, it is just the screen of my app that doesn't show any data. I am using a view pager with 2 fragments and this issue is the same for both.
Here is my FragmentActivity, I will post just one since issue is the same

public class TechNewsFragment extends Fragment {
private SwipeRefreshLayout mSwipeRefreshLayout;
private TextView mErrorMessage;
private NewsAdapter mNewsAdapter;
ArrayList<News> news;
NetworkInfo info;
//    The Loader takes in a bundle
Bundle sourceBundle = new Bundle();

private final String LOG_TAG = MainActivity.class.getSimpleName();

private static final String TECH_NEWS_QUERY_URL = "query";
private static final String TECH_NEWS_SOURCE = "techcrunch";
private static final int TECH_NEWS_LOADER = 22;

private RecyclerView mRecyclerView;

public TechNewsFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_news, container, false);
    mErrorMessage = (TextView) view.findViewById(R.id.tv_error_message);
    mRecyclerView = (RecyclerView) view.findViewById(R.id.recycler_view_main);
    mSwipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipeRefresh);

    mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));

    getActivity().getSupportLoaderManager().initLoader(TECH_NEWS_LOADER, null, new NewsDataLoader());

    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            Log.v(LOG_TAG, "Refreshing");
            restartLoader();
            mSwipeRefreshLayout.setColorSchemeResources(
                    R.color.colorPrimary,
                    R.color.colorPrimaryDark);
        }
    });

    return view;
}

private boolean isConnected(){
    ConnectivityManager cm = (ConnectivityManager) getActivity()
            .getSystemService(CONNECTIVITY_SERVICE);

    info = cm.getActiveNetworkInfo();

    return info != null && info.isConnectedOrConnecting();
}

private int anyRandomInt(Random random) {
    return random.nextInt();
}

private void restartLoader() {
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            URL techNewsUrl = TechNetworkUtils.buildUrl(TECH_NEWS_SOURCE);
            sourceBundle.putString(TECH_NEWS_QUERY_URL, techNewsUrl.toString());

            Random random = new Random();
            int uniqueId = anyRandomInt(random); //Generates a new ID for each loader call;

//                    sourceBundle.putString("query", s);]

            LoaderManager loaderManager = getActivity().getSupportLoaderManager();

            if (loaderManager.getLoader(TECH_NEWS_LOADER) == null) {
                loaderManager.initLoader(uniqueId, sourceBundle, new NewsDataLoader());
            } else {
                loaderManager.restartLoader(TECH_NEWS_LOADER, sourceBundle, new
                        NewsDataLoader());
            }
        }
    }, 5000);
    mSwipeRefreshLayout.setRefreshing(false);
    Log.v(LOG_TAG, "Finished refreshing");
}

private void showErrorScreen(){
    mErrorMessage.setVisibility(View.VISIBLE);
    mRecyclerView.setVisibility(View.INVISIBLE);
    mErrorMessage.setText(getString(R.string.internet_error));
}

`public class NewsDataLoader implements LoaderManager.LoaderCallbacks<ArrayList<News>> {
    @Override
    public Loader<ArrayList<News>> onCreateLoader(int id, final Bundle args) {
        if (isConnected()){
            mErrorMessage.setVisibility(View.INVISIBLE);
            mRecyclerView.setVisibility(View.VISIBLE);
            return new AsyncTaskLoader<ArrayList<News>>(getActivity()) {
                ArrayList<News> mNewsData;

                @Override
                protected void onStartLoading() {
                    super.onStartLoading();
                    if (mNewsData != null){
                        deliverResult(mNewsData);
                    }else{
                        forceLoad();
                        mSwipeRefreshLayout.setRefreshing(true);
                    }
                }

                @Override
                public ArrayList<News> loadInBackground() {
                    try {
                        ArrayList<News> news = TechNetworkUtils.parseJSON(TECH_NEWS_SOURCE);
                        return news;
                    } catch (IOException e) {
                        e.printStackTrace();
                        return null;
                    }
                }

                public void deliverResult(ArrayList<News> data) {
                    mNewsData = data;
                    super.deliverResult(data);
                }
            };
        }else{
            showErrorScreen();
            return null;
        }
    }

    @Override
    public void onLoadFinished(Loader<ArrayList<News>> loader, ArrayList<News> data) {
        mSwipeRefreshLayout.setRefreshing(false);
        if (null == data) {
            showErrorScreen();
        } else {
            mErrorMessage.setVisibility(View.INVISIBLE);
            mRecyclerView.setVisibility(View.VISIBLE);
            if (news != null) {
//                    news.clear();
                news.addAll(data);
                mNewsAdapter = new NewsAdapter(news);
                mRecyclerView.setAdapter(mNewsAdapter);
                mNewsAdapter.notifyDataSetChanged();
            } else {
                news = data;
            }
            Log.i(LOG_TAG + "  this is the data", data.toString());
// Array of objects shows in the log
        }
    }

    @Override
    public void onLoaderReset(Loader<ArrayList<News>> loader) {
//            loader.forceLoad();
    }

}

}`

This is my adapter class

public class NewsAdapter extends
RecyclerView.Adapter<NewsAdapter.NewsHolder> {

//    Variable used to reference the model
private ArrayList<News> mNews = new ArrayList<>();

//    NewsHolder class that extends the ViewHolder
public static class NewsHolder extends RecyclerView.ViewHolder{
    private TextView mNewsTextView;
    private TextView mTimeStampTextView;

//   Constructor to set the views
    public NewsHolder(View itemView){
        super(itemView);
        mNewsTextView = (TextView) itemView.findViewById(R.id.news_tv);
        mTimeStampTextView = (TextView) itemView.findViewById(R.id.time_tv);
    }
}

//    Constructor to set the adapter
public NewsAdapter(ArrayList<News> news){
    mNews = news;
}

@Override
public NewsHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view =
LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_view,
parent, false);
    return new NewsHolder(view);
}

@Override
public void onBindViewHolder(NewsHolder holder, int position) {
    holder.mNewsTextView.setText(mNews.get(position).getNews());
    holder.mTimeStampTextView.setText(mNews.get(position).getTime());
}

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

This is class to parse JSON and handle network connectivity

public class TechNetworkUtils {

private static final String LOG_TAG = MainActivity.class.getSimpleName();

public static ArrayList<News> parseJSON(String source) throws IOException {
    URL url = buildUrl(source);
    String jsonResult = getResponseFromHttpUrl(url);

    ArrayList<News> news = new ArrayList<>();

    try{
        JSONObject jsonObject = new JSONObject(jsonResult);
        JSONArray jsonArray = jsonObject.getJSONArray("articles");

        if (jsonArray != null){
            for (int i = 0; i < jsonArray.length(); i++){
                JSONObject article = jsonArray.getJSONObject(i);
                String title = article.getString("title");
                String time = article.getString("publishedAt");
                news.add(new News(title, time));
                Log.i(LOG_TAG, title);
                Log.i(LOG_TAG, time);
            }
        }

    }catch (JSONException | NullPointerException e){
        e.printStackTrace();
        return null;
    }
    return news;
}

public static URL buildUrl(String techNewsSource){
    final String TECH_NEWS_BASE_URL = "https://newsapi.org/v1/articles";
    final String PARAM_SOURCE = "source";
    final String PARAM_SORT_BY = "sortBy";
    final String latest = "latest";
    final String PARAM_API_KEY = "apiKey";
    final String KEY = "3431d57e51a04c1d967e2eb96c99fd1a";

    Uri builtUri = Uri.parse(TECH_NEWS_BASE_URL).buildUpon()
            .appendQueryParameter(PARAM_SOURCE, techNewsSource)
            .appendQueryParameter(PARAM_SORT_BY, latest)
            .appendQueryParameter(PARAM_API_KEY, KEY)
            .build();

    Log.i(LOG_TAG, builtUri.toString());

    URL url = null;
    try{
        url = new URL(builtUri.toString());
    }catch (MalformedURLException e){
        e.printStackTrace();
    }
    return url;
}

public static String getResponseFromHttpUrl(URL url) throws IOException{
    HttpURLConnection urlConnection = null;
    String newsJsonStr = null;
    BufferedReader reader = null;

    try{
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setReadTimeout(15000);
        urlConnection.setConnectTimeout(10000);
        urlConnection.setRequestMethod("GET");
        urlConnection.setDoOutput(false);
        urlConnection.setDoInput(true);
        urlConnection.connect();

        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();
        if(inputStream == null){
            return null;
        }

        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        while ((line = reader.readLine()) != null){
            buffer.append(line + "\n");
        }

        if (buffer.length() == 0){
            return null;
        }

        newsJsonStr = buffer.toString();

    }catch(IOException e){
        Log.e(LOG_TAG, "Error fetching data", e);
        return null;
    }finally{
        if (urlConnection != null){
            urlConnection.disconnect();
        }
        if (reader != null){
            try{
                reader.close();
            }catch (IOException e){
                Log.e(LOG_TAG, "Error closing stream", e);
            }
        }
    }
    return newsJsonStr;
}
}

This is my pojo class

public class News {
private String mNews;
private String mTime;

public News(String news, String time){
    mNews = news;
    mTime = time;
}

public String getNews() {
    return mNews;
}

public String getTime() {
    return mTime;
}
}`

This is my list_item_layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/title_frame">

    <TextView
        android:padding="16dp"
        android:layout_width="match_parent"
        android:layout_height="64dp"
        android:id="@+id/news_tv"
        tools:text="Get exciting news here"/>

</FrameLayout>
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end">

    <TextView
        android:id="@+id/time_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="8dp"
        android:paddingRight="16dp"
        tools:text="12:00pm"/>
</FrameLayout>

</LinearLayout>

This is my log.i

  /*  06-06 21:35:25.834 1092-1092/com.ire.blogbot E/dalvikvm: Could not
 find
class 'android.graphics.drawable.RippleDrawable', referenced from method
android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
06-06 21:35:25.834 1092-1092/com.ire.blogbot W/dalvikvm: VFY: unable to
resolve instanceof 146 (Landroid/graphics/drawable/RippleDrawable;) in
Landroid/support/v7/widget/AppCompatImageHelper;
06-06 21:35:25.922 1092-1106/com.ire.blogbot I/MainActivity:
https://newsapi.org/v1/articles?source=entertainment-
weekly&sortBy=top&apiKey=3431d57e51a04c1d967e2eb96c99fd1a
06-06 21:35:25.934 1092-1107/com.ire.blogbot I/MainActivity:
https://newsapi.org/v1/articles?
source=techcrunch&sortBy=latest&apiKey=3431d57e51a04c1d967e2eb96c99fd1a
06-06 21:35:26.042 1092-1092/com.ire.blogbot W/EGL_genymotion:
eglSurfaceAttrib not implemented
06-06 21:35:26.226 376-423/system_process I/ActivityManager: Displayed
com.ire.blogbot/.activity.MainActivity: +606ms
06-06 21:35:26.270 376-449/system_process I/qtaguid: Failed write_ctrl(s 0
10021) res=-1 errno=1
06-06 21:35:26.270 376-449/system_process W/NetworkManagementSocketTagger:
setKernelCountSet(10021, 0) failed with errno -1
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: How can tech
companies treat their contractors better?
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: 2017-06-
06T21:19:28Z
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: Audi is the
first to test autonomous vehicles in New York
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: 2017-06-
06T20:58:34Z
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: Bragi’s Dash
Pro is a sophisticated and smart AirPods alternative
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: 2017-06-
06T20:05:41Z
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: As the Surface
line courts creatives, Apple pushes back with the iMac and iPad Pro
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: 2017-06-
06T20:04:19Z
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: What Silicon
Valley can learn from Lebanon’s women in tech
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: 2017-06-
06T20:00:53Z
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: Matt Mitchell
of CryptoHarlem is building an open source tool to help organizations
prepare for data breaches
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: 2017-06-
06T19:29:04Z
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: Pinterest
raises $150M at a $12.3B valuation as it makes a full press into
visual search
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: 2017-06-
06T19:27:05Z
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: Tulip, the app
platform for manufacturers, picks up $13 million from NEA
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: 2017-06-
06T18:45:34Z
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: Take a look at
these first pictures of Fisker’s $130K EMotion electric car
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: 2017-06-
06T18:27:57Z
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: iOS 11 will
help you free up storage on your iPhone through personalized suggestions
06-06 21:35:27.182 1092-1107/com.ire.blogbot I/MainActivity: 2017-06-
06T18:22:33Z
06-06 21:35:27.182 1092-1092/com.ire.blogbot
I/MainActivity  this is the data: [com.ire.blogbot.model.News@536e8250,
com.ire.blogbot.model.News@536e65c0, com.ire.blogbot.model.News@536d157c,
com.ire.blogbot.model.News@536e80ec, com.ire.blogbot.model.News@536e80f8,
com.ire.blogbot.model.News@536e8104, com.ire.blogbot.model.News@536e8110,
com.ire.blogbot.model.News@536e811c, com.ire.blogbot.model.News@536e8128,
com.ire.blogbot.model.News@536e8134]
06-06 21:35:27.202 1092-1106/com.ire.blogbot I/MainActivity:
{"status":"ok","source":"entertainment-weekly","sortBy":"top","articles":
[{"author":null,"title":"The Zodiac Killer: How a first-time filmmaker
attempted to catch the serial
murderer","description":null,"url":"http://zodiactruecrime.ew.com/","urlT
oImage":null,"publishedAt":null},{"author":"Maureen Lee Lenker","title":"Sam
Smith teases return to the recording studio with
new photos","description":"","url":"http://ew.com/music/2017/06/06/sam-
smith-teases-new-
album/","urlToImage":"http://i0.wp.com/ewedit.files.wordpress.com/2017/06/g
ettyimages-521740878.jpg?
 crop=0px%2C82px%2C2700px%2C1418px&resize=1200%2C630&ssl=1","publishedAt":"2
017-06-06T21:22:08Z"},{"author":"Marisa Marcellino","title":"Highest-
grossing
Broadway shows of
all time","description":"","url":"http://ew.com/theater/2017/06/06/highest-
grossing-broadway-shows-of-all-
 time/","urlToImage":"http://i1.wp.com/ewedit.files.wordpress.com/2017/03/li
onking.jpg?
 crop=0px%2C42px%2C2700px%2C1419px&resize=1200%2C630&ssl=1","publishedAt":"2
017-06-06T19:52:02Z"},{"author":"Kyle Fowle","title":"'House of Cards'
Recap:
How Far Is Claire Willing to Go to Secure the
Presidency?","description":"With threats forming all around them, Frank and
Claire take violent action to secure their
legacy","url":"http://ew.com/recap/house-of-cards-season-5-episode-
 12/","urlToImage":"http://i0.wp.com/ewedit.files.wordpress.com/2017/06/hoc_
512_unit_01846r.jpg?
 crop=3px%2C105px%2C2699px%2C1418px&resize=1200%2C630&ssl=1","publishedAt":"
2017-06-06T19:49:12Z"},{"author":"Nivea Serrao","title":"Selena Gomez
responds
to ’13 Reasons Why’ controversy","description":"'This is happening every
day'","url":"http://ew.com/tv/2017/06/06/selena-gomez-13-reasons-why-
controversy-
 2/","urlToImage":"http://i1.wp.com/ewedit.files.wordpress.com/2017/04/13rw_
113_01153r.jpg?
 crop=0px%2C53px%2C2700px%2C1418px&resize=1200%2C630&ssl=1","publishedAt":"2
017-06-06T19:45:59Z"},{"author":"Ruth Kinane","title":"‘Hollywood Game
Night’
teaser: ‘This Is Us,’ ‘Veep,’ ‘Walking Dead’ casts ready
for battle","description":"Jane Lynch returns to
host","url":"http://ew.com/tv/2017/06/06/hollywood-game-night-teaser-this-
is-us-veep-walking-dead-
 casts/","urlToImage":"http://i1.wp.com/ewedit.files.wordpress.com/2017/06/h
ollywoodgame.jpg?
 crop=0px%2C21px%2C2700px%2C1419px&resize=1200%2C630&ssl=1","publishedAt":"2
017-06-06T19:30:49Z"},{"author":"Joey Nolfi","title":"Watch Jerry Seinfeld
refuse a hug from Kesha","description":"\"I don't know who that was... I
wish her the best,\" the 63-year-old
said","url":"http://ew.com/news/2017/06/06/jerry-seinfeld-kesha-
 hug/","urlToImage":"http://i0.wp.com/ewedit.files.wordpress.com/2017/06/sei
nfeldkesha.jpg?
 crop=0px%2C13px%2C3200px%2C1681px&resize=1200%2C630&ssl=1","publishedAt":"2
017-06-06T19:05:57Z"},{"author":"Maureen Lee Lenker","title":"Tonys 2017:
Watch
performances from this year’s Best
 Musical nominees","description":"","url":"http://ew.com/theater/2017/06/06/
tonys-2017-nominations-best-musical-
 performances/","urlToImage":"http://i2.wp.com/ewedit.files.wordpress.com/20
17/0
6/deh-ben-platt-4449-photo.jpg?
 crop=0px%2C382px%2C2700px%2C1419px&resize=1200%2C630&ssl=1","publishedAt":"
2017
-06-06T19:00:59Z"},{"author":"Ray Rahman","title":"‘Broad City’ returns
under a ‘cloud of doom,’ stars tease","description":"Plus: RuPaul makes a
'f---ing titillating' and 'godlike'
cameo","url":"http://ew.com/tv/2017/06/06/broad-city-season-4-
 winter/","urlToImage":"http://i2.wp.com/ewedit.files.wordpress.com/2017/06/
broadcity.jpg?
 crop=0px%2C87px%2C2700px%2C1419px&resize=1200%2C630&ssl=1","publishedAt":"2
017-06-06T18:56:12Z"},{"author":"Nivea Serrao","title":"How ‘The Moth’
podcast
turned storytelling into a
 worldwide movement","description":"","url":"http://ew.com/podcasts/2017/06/
06/the-moth-podcast-20th-
 anniversary/","urlToImage":"http://i1.wp.com/ewedit.files.wordpress.com/201
7/06/gettyimages-530299778.jpg?
crop=0px%2C18px%2C1800px%2C945px&resize=1200%2C630","publishedAt":"2017-
06-06T18:48:15Z"}]}
06-06 21:35:33.406 376-386/system_process I/ActivityManager: No longer want
com.android.exchange (pid 870): hidden #16
06-06 21:41:36.890 55-55/? W/Genyd: Can't parse request
06-06 21:41:36.958 376-466/system_process I/ClipboardService: Got clipboard
for user=0
06-06 21:41:36.958 376-466/system_process I/ClipboardService: Got clipboard
for user=0
06-06 21:41:36.958 376-389/system_process I/ClipboardService: Got clipboard
for user=0
06-06 21:41:36.958 376-389/system_process I/ClipboardService: Got clipboard
for user=0
06-06 21:41:36.958 376-389/system_process I/ClipboardService: Got clipboard
for user=0
06-06 21:41:37.158 376-466/system_process I/ClipboardService: Got clipboard
for user=0
06-06 21:41:37.158 376-466/system_process I/ClipboardService: Got clipboard
for user=0
06-06 21:41:37.162 376-389/system_process I/ClipboardService: Got clipboard
for user=0
06-06 21:41:37.162 376-389/system_process I/ClipboardService: Got clipboard
for user=0
06-06 21:41:37.162 376-389/system_process I/ClipboardService: Got clipboard
for user=0

I need the data to display automatically when the app is launched and refresh when onSwipeRefreshLayout is called.

Body:
I have run your project and I didn't get the error which you have posted from logcat instead I've got NullPointerException in this line of code:

String techNewsUrlString = args.getString(TECH_NEWS_QUERY_URL);

So I replaced the args with your sourceBundle and that fix the error:

String techNewsUrlString = sourceBundle.getString(TECH_NEWS_QUERY_URL);

Second issue was in your fragment_news xml code. Your TextView occupied all space and there wasn't room for Recyclerview so I made some changes:

  <?xml version="1.0" encoding="utf-8"?>
 <android.support.v4.widget.SwipeRefreshLayout
 xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:id="@+id/swipeRefresh"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/tv_error_message"
    android:text="Oops! Couldn't connect to a network"
    android:gravity="center"
    android:layout_margin="32dp"
    android:textSize="16sp"
    android:fontFamily="monospace"
    android:visibility="invisible"/>
<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
 </RelativeLayout>
</android.support.v4.widget.SwipeRefreshLayout>

And your project should work now.


来源: stackexchange

问:
Django Unique Together (with foreign keys)
I have a situation where I want to use the Meta options of unique_together to enforce a certain rule, here's the intermediary model:

class UserProfileExtension(models.Model):
    extension = models.ForeignKey(Extension, unique=False)
    userprofile = models.ForeignKey(UserProfile, unique=False)
    user = models.ForeignKey(User, unique=False)

    class Meta:
        unique_together = (("userprofile", "extension"),
                           ("user", "extension"),
                           # How can I enforce UserProfile's Client
                           # and Extension to be unique? This obviously
                           # doesn't work, but is this idea possible without
                           # creating another FK in my intermediary model
                           ("userprofile__client", "extension"))
```

<p>and here's UserProfile:</p>

<pre class="lang-py prettyprint-override"><code>class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    client = models.ForeignKey(Client)
</code>```

Thanks.

答:
You can't.

The unique_together clause is directly translated to the SQL unique index. And you can only set those on columns of a single table, not a combination of several tables.

You can add validation for it yourself though, simply overwrite the validate_unique method and add this validation to it.

Docs: http://docs.djangoproject.com/en/dev/ref/models/instances/#django.db.models.Model.validate_unique

ContentLicense: CC BY-SA 3.0

Body:
I have a situation where I want to use the Meta options of unique_together to enforce a certain rule, here's the intermediary model:

class UserProfileExtension(models.Model):
    extension = models.ForeignKey(Extension, unique=False)
    userprofile = models.ForeignKey(UserProfile, unique=False)
    user = models.ForeignKey(User, unique=False)

    class Meta:
        unique_together = (("userprofile", "extension"),
                           ("user", "extension"),
                           # How can I enforce UserProfile's Client
                           # and Extension to be unique? This obviously
                           # doesn't work, but is this idea possible without
                           # creating another FK in my intermediary model
                           ("userprofile__client", "extension"))

and here's UserProfile:

class UserProfile(models.Model):
    user = models.ForeignKey(User, unique=True)
    client = models.ForeignKey(Client)

Thanks.

ContentLicense: CC BY-SA 2.5


问:
Detecting a touch with Swift/SKScene
I'm trying to figure out how to detect a touch anywhere on the screen with a subclass of SKScene so that I can transition. How do I do so?

Thanks

答:
```<code>       override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

      let location = touch.location(in: self)

      print(location)

     //if your touch location = a button or anything it transitions to a new scene
       if location = //Startbutton {
       let transition = SKTransition.reveal(with: .down, duration: 0.75)
     let gameScene = GameScene(size: size)
     gameScene.scaleMode = scaleMode
     view?.presentScene(gameScene, transition: transition)
</code>```

Prints the users touch location... hope that helps a bit m8

Title: Detecting a touch with Swift/SKScene

Body:
       override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

      let location = touch.location(in: self)

      print(location)

     //if your touch location = a button or anything it transitions to a new scene
       if location = //Startbutton {
       let transition = SKTransition.reveal(with: .down, duration: 0.75)
     let gameScene = GameScene(size: size)
     gameScene.scaleMode = scaleMode
     view?.presentScene(gameScene, transition: transition)

Prints the users touch location... hope that helps a bit m8


问:
How do I handle class hierarchies where some subclasses are IDisposable and others are not?
Consider I have a base interface, IInterface. I have to classes which implement IInterface, ClassA and ClassB, as such.

```<code>public interface IInterface
{
}

public class ClassA : IInterface
{
}

public class ClassB : IInterface, IDisposable
{
}
</code>```

Note that ClassB is IDisposable and ClassA is not. Now, if I want to create a List<IInterface> which is filled from a factory, how do I handle disposing of the disposable elements? Is it necessary to create a separate List<IDisposable> then filter out the list as the objects are constructed (or after construction)? Should I just IInterface IDisposable with a base abstract class with a default implementation (until C#7 adds default interface implementations)?

I'm not sure what is all of the easiest to utilize and clearest to read in the future. It seems that making all interfaces in which a potential child may be disposable into an IDisposable is a potentially annoying practice. Also it requires having bases with empty dispose implementations, which also seems less than ideal.

答:
You have to check if that instance implements IDisposable then call it.
Example:

```<code>    foreach(var item in listOfClasses)
    {
       var disposableItem = item as IDisposable;

       if(disposableItem != null)
          disposableItem.Dispose();

     ....
    }
</code>```

Is it necessary to create a separate List then filter out the list as the objects are constructed (or after construction)?

That is not necessary. Just create your list like you initially stated and check for the disposable items like I have shown above.

Does this help?

Body:
Consider I have a base interface, IInterface. I have to classes which implement IInterface, ClassA and ClassB, as such.

public interface IInterface
{
}

public class ClassA : IInterface
{
}

public class ClassB : IInterface, IDisposable
{
}

Note that ClassB is IDisposable and ClassA is not. Now, if I want to create a List<IInterface> which is filled from a factory, how do I handle disposing of the disposable elements? Is it necessary to create a separate List<IDisposable> then filter out the list as the objects are constructed (or after construction)? Should I just IInterface IDisposable with a base abstract class with a default implementation (until C#7 adds default interface implementations)?

I'm not sure what is all of the easiest to utilize and clearest to read in the future. It seems that making all interfaces in which a potential child may be disposable into an IDisposable is a potentially annoying practice. Also it requires having bases with empty dispose implementations, which also seems less than ideal.

Body:
You have to check if that instance implements IDisposable then call it.
Example:

    foreach(var item in listOfClasses)
    {
       var disposableItem = item as IDisposable;

       if(disposableItem != null)
          disposableItem.Dispose();

     ....
    }

Is it necessary to create a separate List then filter out the list as the objects are constructed (or after construction)?

That is not necessary. Just create your list like you initially stated and check for the disposable items like I have shown above.

Does this help?


问:
Firebase Javascript, how to use variables from inside ref function?
I'm attempting to access a variable from within a datasnapshot:

```<code>  getEmail() {
    var test = firebase.database().ref('/users/' + user).once('value')
    .then(function(snapshot) {
        var email = snapshot.val().email;
        });
        console.log(email);
    }
</code>```

That console.log doesn't return the database value, and I am also unable to access that email variable elsewhere in my code.

答:
there are 2 possible solutions: (both mentioned by Sterling in comments)

1) the log statement is not in the scope of the .then method:

getEmail () {
  var test = firebase.database().ref('/users/' + user).once('value')
    .then(function (snapshot) {
      var email = snapshot.val().email
      console.log(email)
    })
}```
</div>
</div>
</p>

<p>2.) you could return the <code>email</code> variable in the <code>.then</code> method and log the <code>test</code> variable:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>getEmail () {
  var test = firebase.database().ref('/users/' + user).once('value')
    .then(function (snapshot) {
      var email = snapshot.val().email
      return email
    })
  console.log(test)
}</code>```

**) clearest way IMO is like this:

getEmail () {
  var email = firebase.database().ref('/users/' + user).once('value')
    .then(function (snapshot) {
      return snapshot.val().email
    })
  console.log(email)
}```

Body:
I'm attempting to access a variable from within a datasnapshot:

  getEmail() {
    var test = firebase.database().ref('/users/' + user).once('value')
    .then(function(snapshot) {
        var email = snapshot.val().email;
        });
        console.log(email);
    }

That console.log doesn't return the database value, and I am also unable to access that email variable elsewhere in my code.

Body:
there are 2 possible solutions: (both mentioned by Sterling in comments)

1) the log statement is not in the scope of the .then method:

getEmail () {
  var test = firebase.database().ref('/users/' + user).once('value')
    .then(function (snapshot) {
      var email = snapshot.val().email
      console.log(email)
    })
}

2.) you could return the email variable in the .then method and log the test variable:

getEmail () {
  var test = firebase.database().ref('/users/' + user).once('value')
    .then(function (snapshot) {
      var email = snapshot.val().email
      return email
    })
  console.log(test)
}

**) clearest way IMO is like this:

getEmail () {
  var email = firebase.database().ref('/users/' + user).once('value')
    .then(function (snapshot) {
      return snapshot.val().email
    })
  console.log(email)
}


问:
How to output to console in real time in Javascript?
In Javascript, when you write a piece of code like the one below, it seems like the computer will first complete the entire loop 100 000 times (which can take a second or two) and THEN dump all 100 000 lines in the console in one shot. How can I make it so that the computer will update the console one line at a time, with each pass thru the loop?

To clarify, I would like to, in effect, be able to see what the computer is doing AS it is doing it, and not once it has finished doing it.

for (var i = 1; i <= 100000; i++) {
  console.log(i);
}```

答:
One could feed an array of Promises to an Observable in order to achieve the desired outcome. Promises are now native to JavaScript and you can get the Observable from the RxJS library.

Here is an example:

const array = [];

// This could also be a for of loop or a .map() function
for (let i = 0; i <= 25; i++) {
  const promise = new Promise((resolve) => {

    // This could be any synchronous or asynchronous code
    setTimeout(() => {
      resolve(i);
    }, 1000 * i);
  });

  array.push(promise);
}

var observable = Rx.Observable.from(array);

observable.subscribe((promise) => {
  promise.then(result => console.log(result));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script></code>```

Body:
One could feed an array of Promises to an Observable in order to achieve the desired outcome. Promises are now native to JavaScript and you can get the Observable from the RxJS library.

Here is an example:

const array = [];

// This could also be a for of loop or a .map() function
for (let i = 0; i <= 25; i++) {
  const promise = new Promise((resolve) => {

    // This could be any synchronous or asynchronous code
    setTimeout(() => {
      resolve(i);
    }, 1000 * i);
  });

  array.push(promise);
}

var observable = Rx.Observable.from(array);

observable.subscribe((promise) => {
  promise.then(result => console.log(result));
});

<script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>


问:
Is ASP.net C# codebehind considered to be server-side or client-side?
I want to say it is server-side just from my reading and understanding, but I was hoping for a bit of clarification. Thanks. </p>

答:
Your codebehind is written in c#.  Anything written in c# runs server side.  After all, your web pages can be displayed on any device, including devices that lack a .NET CLR; how could they possibly run on an iPhone?

Also, anything that references a .NET object also must run server-side.  After all, the client can't talk to .NET objects if it doesn't have a CLR.  When you see markup like this

```<code><ASP:Button runat="server" id="MyButton">
</code>```

...it means that the code is setting properties of a .NET object (in this case, a button).  All that is server side code.

Your ASP.NET controls emit HTML markup (among other things) which are returned to the browser and "executed" (parsed) there.  The HTML usually isn't present in your code at all; it is generated in real time by your code, usually via a method called Render.

However, markup that is not marked runat="server" can be inserted into your web pages, and this markup will get sent to the browser along with the generated HTML.  For example, only the second line in this example is server-side:

```<code><DIV id="This_Is_Client_Side">
    <ASP:Button id="This_Is_Server_Side" runat="server" />
</DIV>
</code>```

In addition, any Javascript or CSS files in your project will be sent to the browser to run there.

Pretty much everything else is server-side code. Including codebehind.

Body:
Your codebehind is written in c#.  Anything written in c# runs server side.  After all, your web pages can be displayed on any device, including devices that lack a .NET CLR; how could they possibly run on an iPhone?

Also, anything that references a .NET object also must run server-side.  After all, the client can't talk to .NET objects if it doesn't have a CLR.  When you see markup like this

<ASP:Button runat="server" id="MyButton">

...it means that the code is setting properties of a .NET object (in this case, a button).  All that is server side code.

Your ASP.NET controls emit HTML markup (among other things) which are returned to the browser and "executed" (parsed) there.  The HTML usually isn't present in your code at all; it is generated in real time by your code, usually via a method called Render.

However, markup that is not marked runat="server" can be inserted into your web pages, and this markup will get sent to the browser along with the generated HTML.  For example, only the second line in this example is server-side:

<DIV id="This_Is_Client_Side">
    <ASP:Button id="This_Is_Server_Side" runat="server" />
</DIV>

In addition, any Javascript or CSS files in your project will be sent to the browser to run there.

Pretty much everything else is server-side code. Including codebehind.


问:
SmartSVN - files from multiple branches
I have one of my project branches open with SmartSVN, but one of the files is showing its branch as "trunk" which the rest show the correct branch name. I'm not sure how this happened but would like to fix it. What happened and how can I fix it?</p>

答:
Actaully, this is a feature of Subversion.  Yep, want a particular branch for this folder in your working copy, just switch to it.  It's called a mixed working copy.  The only caveat for this to work, all paths have to be pointed to the same repository.  Now, the fun part is, most people don't use this feature intentionally but somehow manage to stumble upon it through some way or another.

Stumbling on this feature usually involves a switch on a working copy that doesn't get fully switched, often in which is caused by a terminated connection to the Subversion server, resources unavailable on the local machine and the command fails or times out, or the command or application was terminated by the user in the middle of a switch.

No matter the cause, the best solution to resolve this mixed working copy, go to the head of working copy and do another svn switch to the URL you're trying to use.  Just make sure the switch is complete before working on it and before you close SmartSVN.

Title: SmartSVN - files from multiple branches


问:
Ionic 3 / auth0 error when running in browser
I'm trying to follow the Ionic quickstart for here: https://auth0.com/docs/quickstart/native/ionic2

When I do this ( or run the sample ) and run "ionic serve" I get the following error when the login button is clicked

```<code>TypeError: Cannot read property 'isAvailable' of undefined
    at Function.Browser.isAvailable (http://localhost:8100/build/main.js:115566:30)
    at getAgent (http://localhost:8100/build/main.js:115598:23)
    at CordovaAuth.authorize (http://localhost:8100/build/main.js:64570:3)
    at AuthService.login (http://localhost:8100/build/main.js:64460:16)
    at Object.eval [as handleEvent] (ng:///AppModule/HomePage.ngfactory.js:39:29)
    at handleEvent (http://localhost:8100/build/main.js:12083:138)
    at callWithDebugContext (http://localhost:8100/build/main.js:13291:42)
    at Object.debugHandleEvent [as handleEvent] (http://localhost:8100/build/main.js:12879:12)
    at dispatchEvent (http://localhost:8100/build/main.js:9058:21)
    at http://localhost:8100/build/main.js:9648:38
    at HTMLButtonElement.<anonymous> (http://localhost:8100/build/main.js:39395:53)
    at t.invokeTask (http://localhost:8100/build/polyfills.js:3:12256)
    at Object.onInvokeTask (http://localhost:8100/build/main.js:4394:37)
    at t.invokeTask (http://localhost:8100/build/polyfills.js:3:12177)
    at n.runTask (http://localhost:8100/build/polyfills.js:3:7153)
</code>```

Seems to work OK in ios but not browser. Why is this? Is it because auth0 sdk now uses the safariviewcontroller instead of InAppBrowser?

答:
It is mentioned in the page why:

Please note that PKCE authentication requires testing on either an emulated or real device. Attempting authentication when testing in the browser will fail because PKCE requires a device browser.

Body:
I'm trying to follow the Ionic quickstart for here: https://auth0.com/docs/quickstart/native/ionic2

When I do this ( or run the sample ) and run "ionic serve" I get the following error when the login button is clicked

TypeError: Cannot read property 'isAvailable' of undefined
    at Function.Browser.isAvailable (http://localhost:8100/build/main.js:115566:30)
    at getAgent (http://localhost:8100/build/main.js:115598:23)
    at CordovaAuth.authorize (http://localhost:8100/build/main.js:64570:3)
    at AuthService.login (http://localhost:8100/build/main.js:64460:16)
    at Object.eval [as handleEvent] (ng:///AppModule/HomePage.ngfactory.js:39:29)
    at handleEvent (http://localhost:8100/build/main.js:12083:138)
    at callWithDebugContext (http://localhost:8100/build/main.js:13291:42)
    at Object.debugHandleEvent [as handleEvent] (http://localhost:8100/build/main.js:12879:12)
    at dispatchEvent (http://localhost:8100/build/main.js:9058:21)
    at http://localhost:8100/build/main.js:9648:38
    at HTMLButtonElement.<anonymous> (http://localhost:8100/build/main.js:39395:53)
    at t.invokeTask (http://localhost:8100/build/polyfills.js:3:12256)
    at Object.onInvokeTask (http://localhost:8100/build/main.js:4394:37)
    at t.invokeTask (http://localhost:8100/build/polyfills.js:3:12177)
    at n.runTask (http://localhost:8100/build/polyfills.js:3:7153)

Seems to work OK in ios but not browser. Why is this? Is it because auth0 sdk now uses the safariviewcontroller instead of InAppBrowser?


问:
Output panel too small in Sublime Text 3 with Material Theme
When I use the default theme of Sublime Text 3, the output panel can be resized normally. But when I switch to Material Theme, I can no longer adjust the size of the output panel. It's just one line height, so I have scroll to up to see the whole result, which is really inconvenient. How can I adjust the settings so that I can still resize the output panel with Material Theme?</p>

答: Just have to Right-click the editing area of an opening file, select Material Theme -> Configuration -> Panels -> tick the material_theme_compact_panel option.


问:
Significance of parameter names in oracle trace files
I am comparing results of two different JDBC drivers of oracle with the help of oracle's SQL tracing capabilities. I am using TKProf to format the results.

When I look at the output of TKProf sometimes I see parameters named prefixed with 'v':

```<code>WHERE start_time BETWEEN  :v0  AND  :v1
</code>```

At other instances the parameters are not prefixed:

```<code>WHERE start_time BETWEEN :1 AND :2
</code>```

I suspect that in second case, query optimizer is not picking some indices.

Is there a hint in the naming convention of parameters?

答: They're private bind variable names picked by the client software; possibly in your Java code the query has between ? and ? which has to be translated to something Oracle will understand. The names are almost irrelevant - certainly nothing to do with indexes or optimisation. I say 'almost' because I'm not sure if Oracle will see them as the same query, or will do separate hard parses of each.

Body:
I am comparing results of two different JDBC drivers of oracle with the help of oracle's SQL tracing capabilities. I am using TKProf to format the results.

When I look at the output of TKProf sometimes I see parameters named prefixed with 'v':

WHERE start_time BETWEEN  :v0  AND  :v1

At other instances the parameters are not prefixed:

WHERE start_time BETWEEN :1 AND :2

I suspect that in second case, query optimizer is not picking some indices.

Is there a hint in the naming convention of parameters?


问:
AJV schema validation for nested object
Functions returns object which looks something like this:

```<code>    {
        "answer": {
           "vehicle_type": 1,
           "message": "Car"
        },
        "model": "VW",
        "color": "red"
    }
</code>```

'Answer' object is always there. Other fields are there based on 'vehicle_type'.

E.g.

if vehicle_type = 1 there are 'model' and 'color'.

if vehicle_type = 2 there are 'engine_count', 'seat_count' and 'wing_count'.

I am trying to write JSON-schema which I will use to validate returned object.

I would like to set 'model' and 'color' as required properties if 'vehicle_type' is 1.
And if 'vehicle_type' is 2, then 'engine_count', 'seat_count' and 'wing_count' are required.

I am using AJV (https://github.com/epoberezkin/ajv) schema validator.

For me, it's problematic because vehicle_type is nested inside 'answer', and properties which I want to mark as required are on the parent object.
In other words, 'validation_type' is not on the same level as 'model' or 'engine_count'.

I already several different approached... I also tried with ajv-keywords (switch, if/else/then) but i didn't have any luck

Any ideas?

答:
You can use "oneOf" property for that.

Where you will have "one of" a vehicle type 1, or a type 2. Type 1 has certain required properties while type 2 has different required properties.

For example:

```<code>{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "http://some.site.somewhere/entry-schema#",
  "oneOf": [
    {"$ref": "#/definitions/type1"},
    {"$ref": "#/definitions/type2"}
  ],
  "definitions": {
    "type1": {
      "type": "object",
      "properties": {
        "answer": {
          "type": "object",
          "properties": {
            "vehicle_type": {
              "type": "integer",
              "enum": [1]
            },
            "message": {
              "type": "string"
            }
          }
        },
        "model": {
          "type": "string"
        },
        "color": {
          "type": "string"
        }
      },
      "required": [
        "model",
        "color"
      ]
    },
    "type2": {
      "type": "object",
      "properties": {
        "answer": {
          "type": "object",
          "properties": {
            "vehicle_type": {
              "type": "integer",
              "enum": [2]
            },
            "message": {
              "type": "string"
            }
          }
        },
        "engine_count": {
          "type": "integer"
        },
        "seat_count": {
          "type": "integer"
        },
        "wing_count": {
          "type": "integer"
        }
      },
      "required": [
        "engine_count",
        "seat_count",
        "wing_count"
      ]
    }
  }
}
</code>```

Title: AJV schema validation for nested object

Body:
Functions returns object which looks something like this:

    {
        "answer": {
           "vehicle_type": 1,
           "message": "Car"
        },
        "model": "VW",
        "color": "red"
    }

'Answer' object is always there. Other fields are there based on 'vehicle_type'.

E.g.

if vehicle_type = 1 there are 'model' and 'color'.

if vehicle_type = 2 there are 'engine_count', 'seat_count' and 'wing_count'.

I am trying to write JSON-schema which I will use to validate returned object.

I would like to set 'model' and 'color' as required properties if 'vehicle_type' is 1.
And if 'vehicle_type' is 2, then 'engine_count', 'seat_count' and 'wing_count' are required.

I am using AJV (https://github.com/epoberezkin/ajv) schema validator.

For me, it's problematic because vehicle_type is nested inside 'answer', and properties which I want to mark as required are on the parent object.
In other words, 'validation_type' is not on the same level as 'model' or 'engine_count'.

I already several different approached... I also tried with ajv-keywords (switch, if/else/then) but i didn't have any luck

Any ideas?

Body:
You can use "oneOf" property for that.

Where you will have "one of" a vehicle type 1, or a type 2. Type 1 has certain required properties while type 2 has different required properties.

For example:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "id": "http://some.site.somewhere/entry-schema#",
  "oneOf": [
    {"$ref": "#/definitions/type1"},
    {"$ref": "#/definitions/type2"}
  ],
  "definitions": {
    "type1": {
      "type": "object",
      "properties": {
        "answer": {
          "type": "object",
          "properties": {
            "vehicle_type": {
              "type": "integer",
              "enum": [1]
            },
            "message": {
              "type": "string"
            }
          }
        },
        "model": {
          "type": "string"
        },
        "color": {
          "type": "string"
        }
      },
      "required": [
        "model",
        "color"
      ]
    },
    "type2": {
      "type": "object",
      "properties": {
        "answer": {
          "type": "object",
          "properties": {
            "vehicle_type": {
              "type": "integer",
              "enum": [2]
            },
            "message": {
              "type": "string"
            }
          }
        },
        "engine_count": {
          "type": "integer"
        },
        "seat_count": {
          "type": "integer"
        },
        "wing_count": {
          "type": "integer"
        }
      },
      "required": [
        "engine_count",
        "seat_count",
        "wing_count"
      ]
    }
  }
}


问:
Undefined symbols for architecture x86_64 linking constexpr std::array
I am getting the error in while linking my object files:

```<code>#include <cstdint>
#include <array>

enum SystemType : uint8_t { AC, DC, HCP, EFF };

template<SystemType TYPE> struct System;

template<>
struct System<AC> {
public:
static constexpr size_t number_of_sockets = 2;
static constexpr std::array<size_t, number_of_sockets> object_per_socket { { 12, 6 } };
};
</code>```

I am using it as below to allocate data into a vector.

```<code>terminal->no_obj_per_system.assign(
            Sytem<AC>::object_per_socket.begin(),
            Sytem<AC>::object_per_socket.end());
</code>```

I am using clang on mac Os.

答:
In C++14 and earlier, static data members must have an out-of-class definition in exactly one translation unit if they are odr-used;  this rule still applies to constexpr members.

This question contains an example with references from the C++14 Standard.

If there is no out-of-class definition provided, and the variable is odr-used, then it is ill-formed with no diagnostic required, which explains why some people don't get a compilation error.  To be on the safe side you should provide a definition, there's no harm doing so even in the case where the variable is not odr-used.

The definition would look like, (NOT in a header file):

```<code>constexpr std::array<size_t, System<AC>::number_of_sockets>  System<AC>::object_per_socket;
</code>```

In C++17 there is a new feature "inline variables", which allows variables to be defined in header files with similar semantics to inline functions, i.e. you're allowed to have multiple matching definitions across translation units, and the compiler/linker will select one as needed.  constexpr variables will be implicitly inline, so your original code will be correct in C++17.  Recent versions of gcc and clang should accept the code with -std=c++1z flag.

Body:
I am getting the error in while linking my object files:

#include <cstdint>
#include <array>

enum SystemType : uint8_t { AC, DC, HCP, EFF };

template<SystemType TYPE> struct System;

template<>
struct System<AC> {
public:
static constexpr size_t number_of_sockets = 2;
static constexpr std::array<size_t, number_of_sockets> object_per_socket { { 12, 6 } };
};

I am using it as below to allocate data into a vector.

terminal->no_obj_per_system.assign(
            Sytem<AC>::object_per_socket.begin(),
            Sytem<AC>::object_per_socket.end());

I am using clang on mac Os.

Body:
In C++14 and earlier, static data members must have an out-of-class definition in exactly one translation unit if they are odr-used;  this rule still applies to constexpr members.

This question contains an example with references from the C++14 Standard.

If there is no out-of-class definition provided, and the variable is odr-used, then it is ill-formed with no diagnostic required, which explains why some people don't get a compilation error.  To be on the safe side you should provide a definition, there's no harm doing so even in the case where the variable is not odr-used.

The definition would look like, (NOT in a header file):

constexpr std::array<size_t, System<AC>::number_of_sockets>  System<AC>::object_per_socket;

In C++17 there is a new feature "inline variables", which allows variables to be defined in header files with similar semantics to inline functions, i.e. you're allowed to have multiple matching definitions across translation units, and the compiler/linker will select one as needed.  constexpr variables will be implicitly inline, so your original code will be correct in C++17.  Recent versions of gcc and clang should accept the code with -std=c++1z flag.


问:
RAII vs. Garbage Collector
I recently watched a great talk by Herb Sutter about "Leak Free C++..." at CppCon 2016 where he talked about using smart pointers to implement RAII (Resource acquisition is initialization) - Concepts and how they solve most of the memory leaks issues.

Now I was wondering. If I strictly follow RAII rules, which seems to be a good thing, why would that be any different from having a garbage collector in C++? I know that with RAII the programmer is in full control of when the resources are freed again, but is that in any case beneficial to just having a garbage collector? Would it really be less efficient? I even heard that having a garbage collector can be more efficient, as it can free larger chunks of memory at a time instead of freeing small memory pieces all over the code.

答:
RAII and garbage collection are intended to solve different problems.

When you use RAII you leave an object on the stack which sole purpose is to clean up whatever it is you want managed (sockets, memory, files, etc.) on leaving the scope of the method.  This is for exception-safety, not just garbage collection, which is why you get responses about closing sockets and freeing mutexes and the like.  (Okay, so no one mentioned mutexes besides me.)  If an exception is thrown, stack-unwinding naturally cleans up the resources used by a method.

Garbage collection is the programmatic management of memory, though you could "garbage-collect" other scarce resources if you'd like. Explicitly freeing them makes more sense 99% of the time.  The only reason to use RAII for something like a file or socket is you expect the use of the resource to be complete when the method returns.

Garbage collection also deals with objects that are heap-allocated, when for instance a factory constructs an instance of an object and returns it.  Having persistent objects in situations where control must leave a scope is what makes garbage collection attractive.  But you could use RAII in the factory so if an exception is thrown before you return, you don't leak resources.

Title: RAII vs. Garbage Collector


问:
Insufficient privileges for password reset
My goal is to allow users to change and reset their own passwords within my application. We do not want users to be redirected to consent pages.

I've followed the instructions defined here:

But I'm running into the following error:

{
  "error": {
    "code": "Authorization_RequestDenied",
    "message": "Insufficient privileges to complete the operation.",
    "innerError": {
      "request-id": "19c43c69-f553-470e-9432-617395f5f8f5",
      "date": "2017-06-01T17:24:11"
    }
  }
}
```

<p>My patch request:</p>

<pre class="lang-json prettyprint-override"><code>PATCH /v1.0/users/2b6c3114-d81b-429d-af7e-c822a456ebba HTTP/1.1
Host: graph.microsoft.com
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJ...xnsYVw
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 73f...d6

{
  "passwordProfile": {
    "password": "w",
    "forceChangePasswordNextSignIn": false
  }
}
</code>```

Here's my graph permissions:

Delegated permissions:

User.Read, User.ReadWrite, Directory.AccessAsUser.All*, Directory.ReadWrite.All*, User.ReadWrite.All*

Application Permissions:

Directory.ReadWriteAll*, User.Read.All*, User.ReadWrite.All*

* Admin Consent Required

I understand that the scope Directory.AccessAsUser.All is required when using the passwordProfile property. Since this isn't available as an application permission, does this mean I have to get access on behalf of a user and use the Authorization Code grant? I don't see any possible way to avoid user consent when using authorization codes to retrieve a token.

EDIT 1

I've tried getting the token using the client_credentials grant_type but I always receive a message that the scope is invalid if I don't use a scope of https://graph.microsoft.com/.default:

POST /tenantid/oauth2/v2.0/token HTTP/1.1
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Postman-Token: 006...85

client_id={id}&scope=https://graph.microsoft.com/User.Read&client_secret={secret}&grant_type=client_credentials
```

答:
So I will caveat this answer with the fact that there may be good reasons for doing what you are doing, but you should be aware of all the things that the organization will lose by bypassing Azure AD sign-in and related features like SSPR.  Please see this excellent blog post that describes some of the things you'll lose - plus while this is still relevant, there are now MORE security features that your customer will lose, like conditional access.

Anyways, assuming you want to press ahead...
For your scenario (an app service that bypasses Azure AD SSPR and change password experiences), there is an option for change password (that it appears we did not document - filing a bug for that) and regrettably nothing I can offer for password reset.  Let me address the first one.

Change Password - in Microsoft Graph (although not documented) you'll find the "changePassword" method on user - ../users/{id}/changePassword, which takes the old password and a new password.  This API works ONLY for the signed-in user (so it requires the delegated OAuth2 code flow).  It requires an admin to consent for Directory.AccessAsUser.All (although we are looking at adding a more granular permission).

Reset password - there is no app-only permission exposed by Microsoft Graph for this. This is an extremely powerful permission to grant to an application.  You've already been given the workaround by support, for an admin to explicitly grant this using powershell.  This grants your app a lot of privileges to your customer's resources. Alternatively, there is a delegated permission (Directory.AccessAsUser.All) that allows an admin user to reset another user's password.  However this wouldn't be a self-service experience.

Hope this helps,

Body:
My goal is to allow users to change and reset their own passwords within my application. We do not want users to be redirected to consent pages.

I've followed the instructions defined here:

But I'm running into the following error:

{
  "error": {
    "code": "Authorization_RequestDenied",
    "message": "Insufficient privileges to complete the operation.",
    "innerError": {
      "request-id": "19c43c69-f553-470e-9432-617395f5f8f5",
      "date": "2017-06-01T17:24:11"
    }
  }
}

My patch request:

PATCH /v1.0/users/2b6c3114-d81b-429d-af7e-c822a456ebba HTTP/1.1
Host: graph.microsoft.com
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJ...xnsYVw
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 73f...d6

{
  "passwordProfile": {
    "password": "w",
    "forceChangePasswordNextSignIn": false
  }
}

Here's my graph permissions:

Delegated permissions:

User.Read, User.ReadWrite, Directory.AccessAsUser.All*, Directory.ReadWrite.All*, User.ReadWrite.All*

Application Permissions:

Directory.ReadWriteAll*, User.Read.All*, User.ReadWrite.All*

* Admin Consent Required

I understand that the scope Directory.AccessAsUser.All is required when using the passwordProfile property. Since this isn't available as an application permission, does this mean I have to get access on behalf of a user and use the Authorization Code grant? I don't see any possible way to avoid user consent when using authorization codes to retrieve a token.

EDIT 1

I've tried getting the token using the client_credentials grant_type but I always receive a message that the scope is invalid if I don't use a scope of https://graph.microsoft.com/.default:

POST /tenantid/oauth2/v2.0/token HTTP/1.1
Host: login.microsoftonline.com
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
Postman-Token: 006...85

client_id={id}&scope=https://graph.microsoft.com/User.Read&client_secret={secret}&grant_type=client_credentials


问:
How Do I read an Excel 2007 spreadsheet with more than 65535 rows?
Here's what my connection string looks like..

```<code>m_conn = new OleDbConnection(String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=" + (char)34 + "Excel 12.0;HDR=YES" + (char)34, m_fileName));
</code>```

When I do a select, I only get 65535 rows back but I know the excel spreadsheet has at least 100,000.  How Do I read the rest of the rows.  Note I have to use OLEDB, no 3rd party tools right now.

Thanks much!

edit: These are Excel 2007/2010 files I'm working with

edit2: Would seem I can actually select all the rows in the spreadsheet if I do a "Select * from worksheet" as opposed to "Select * from worksheet WHERE something"

I guess when you implement a WHERE clause, the resulting rows is capped at 65535

答: You should open such files and save them with compatibility mode turned off. You will get more than 64k in your queries.</p>

Body:
Here's what my connection string looks like..

m_conn = new OleDbConnection(String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=" + (char)34 + "Excel 12.0;HDR=YES" + (char)34, m_fileName));

When I do a select, I only get 65535 rows back but I know the excel spreadsheet has at least 100,000.  How Do I read the rest of the rows.  Note I have to use OLEDB, no 3rd party tools right now.

Thanks much!

edit: These are Excel 2007/2010 files I'm working with

edit2: Would seem I can actually select all the rows in the spreadsheet if I do a "Select * from worksheet" as opposed to "Select * from worksheet WHERE something"

I guess when you implement a WHERE clause, the resulting rows is capped at 65535


问:
C# Getting Runtime error : The process cannot access the file because it is being used by another process
Here is my code:
enter image description here

```<code>using System.IO;

namespace Randoms
{
    public class Program
    {
        public static void Main()
        {
            byte[] buffer = new byte[10240]; // buffer size
            string path = @"C:\Users\RAHUL\Desktop\file.txt";
            using (FileStream source = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                long fileLength = source.Length;
                using (FileStream dest = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
                {
                    long totalBytes = 0;
                    int currentBlockSize = 0;

                    while ((currentBlockSize = source.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        totalBytes += currentBlockSize;
                        double percentage = (double)totalBytes * 100.0 / fileLength;
                        dest.Write(buffer, 0, currentBlockSize);
                    }
                }
            }
        }
    }
}
</code>```

Please check the image which shows the error which I am getting.I have tried to change the FileAccess multiple times but not getting any luck.

答:
Both source and dest are referencing the same file. In the first instance (source) you open it exclusively (ie not shared).

In the second instance (dest) you now want to create the file which you opened in the first instance, but allow it to be shared.

Since the source is already open an in use you cannot write over the top of it using dest.

I think what you may be really want is to have the path parameter for the dest to be different to path parameter for the source, since you are essentially trying to re-write the same data into the same file at the same location right now.

Body:
Here is my code:
enter image description here

using System.IO;

namespace Randoms
{
    public class Program
    {
        public static void Main()
        {
            byte[] buffer = new byte[10240]; // buffer size
            string path = @"C:\Users\RAHUL\Desktop\file.txt";
            using (FileStream source = new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                long fileLength = source.Length;
                using (FileStream dest = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read))
                {
                    long totalBytes = 0;
                    int currentBlockSize = 0;

                    while ((currentBlockSize = source.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        totalBytes += currentBlockSize;
                        double percentage = (double)totalBytes * 100.0 / fileLength;
                        dest.Write(buffer, 0, currentBlockSize);
                    }
                }
            }
        }
    }
}

Please check the image which shows the error which I am getting.I have tried to change the FileAccess multiple times but not getting any luck.


问:
Unable to encode String for URL in Swift 3
I used to develop iOS Apps using Objective-C. Now I have recently migrated to Swift. In my app, I have a button that opens MS Outlook App with the pre-filled Subject and Body.

I did a similar App in Objective-C and used the below code to Encode my String for URL.

```<code>NSString *emailSubject = @"Test Subject";
NSString *encodedSubject = [emailSubject stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
</code>```

Now I am unable to do the same in Swift 3. Below is the code that I tried.

```<code>var subjectText: String = "Test Subject"

var encodedSubject = subjectText.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

var stringURL: String = "ms-outlook://compose?subject=" + subjectText + "&body=TestingEmailNow"
// Convert the string to a URL.
var url = URL(string: stringURL)

// Open the app that responds to the URL scheme (should be Outlook).
UIApplication.shared.openURL(url!)
</code>```

The error that I am getting is below.

fatal error: unexpectedly found nil while unwrapping an Optional value
  2017-06-07 04:29:35.158030+0400 My App[1286:405793] fatal error: unexpectedly found nil while unwrapping an Optional value

I know that this error is coming due to the space in my Subject. I can say this because if I remove the space, I don't even have to encode it. It works directly. What am I doing wrong over here?

答:
You made a simple mistake.

check your line

```<code>var stringURL: String = "ms-outlook://compose?subject=" + subjectText + "&body=TestingEmailNow"
</code>```

you are using subjectText instead of encodedSubject

Complete code:

```<code>var subjectText: String = "Test Subject"

var encodedSubject = subjectText.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

if let encodedSubject = encodedSubject {

    var stringURL: String = "ms-outlook://compose?subject=" + encodedSubject + "&body=TestingEmailNow"

    // Convert the string to a URL.
    var url = URL(string: stringURL)

    if let url = url {
        // Open the app that responds to the URL scheme (should be Outlook).
        UIApplication.shared.openURL(url)
    }
}
</code>```

Body:
I used to develop iOS Apps using Objective-C. Now I have recently migrated to Swift. In my app, I have a button that opens MS Outlook App with the pre-filled Subject and Body.

I did a similar App in Objective-C and used the below code to Encode my String for URL.

NSString *emailSubject = @"Test Subject";
NSString *encodedSubject = [emailSubject stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];

Now I am unable to do the same in Swift 3. Below is the code that I tried.

var subjectText: String = "Test Subject"

var encodedSubject = subjectText.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

var stringURL: String = "ms-outlook://compose?subject=" + subjectText + "&body=TestingEmailNow"
// Convert the string to a URL.
var url = URL(string: stringURL)

// Open the app that responds to the URL scheme (should be Outlook).
UIApplication.shared.openURL(url!)

The error that I am getting is below.

fatal error: unexpectedly found nil while unwrapping an Optional value
  2017-06-07 04:29:35.158030+0400 My App[1286:405793] fatal error: unexpectedly found nil while unwrapping an Optional value

I know that this error is coming due to the space in my Subject. I can say this because if I remove the space, I don't even have to encode it. It works directly. What am I doing wrong over here?

Body:
You made a simple mistake.

check your line

var stringURL: String = "ms-outlook://compose?subject=" + subjectText + "&body=TestingEmailNow"

you are using subjectText instead of encodedSubject

Complete code:

var subjectText: String = "Test Subject"

var encodedSubject = subjectText.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)

if let encodedSubject = encodedSubject {

    var stringURL: String = "ms-outlook://compose?subject=" + encodedSubject + "&body=TestingEmailNow"

    // Convert the string to a URL.
    var url = URL(string: stringURL)

    if let url = url {
        // Open the app that responds to the URL scheme (should be Outlook).
        UIApplication.shared.openURL(url)
    }
}


问:
HTML textarea in Elm where pressing tab adds \t and doesn't change focus
I know how to listen for tab key presses in Elm. And I know how to stop the focus from being changed using onWithOptions:

```<code>textarea
    [ onWithOptions "keydown" (Options False True) <| Decode.map KeyDown keyCode ] []
</code>```

I can then check, in my update function, if the keyCode pressed was a 9, representing a tab. The problem is now the default behavior of a textarea doesn't work. Anything I type doesn't appear in the textarea. Easy enough, I simply add whatever I type to the model and make the value of the textarea the model. Now I have issues with the cursor and, more importantly, clipboard pasting doesn't work...

How do I get tabs to work properly with textareas in Elm? Normally, it would seem to make sense to only call preventDefault() if the tab key was pressed. How can I conditionally call preventDefault() in Elm?

答:
Elm does support conditional event propagation through a Decoder that either succeeds or fails. Simply map the message type you want to react to in your update function:

```<code>succeededIfTabKey : Int -> Decode.Decoder Int
succeededIfTabKey key =
    if key == 9 then
        Decode.succeed key
    else
        Decode.fail "non-tab"

tabPressed : Decode.Decoder Msg
tabPressed =
    Decode.andThen succeededIfTabKey keyCode
        |> Decode.map (always TabPressed)
</code>```

And then use this as your attribute for your input element:

```<code>onWithOptions "keydown" { defaultOptions | preventDefault = True } tabPressed
</code>```

This isn't ideal for all situations. If you want some keydown events to not preventDefault(), and other keydown events to preventDefault(), then you're out of luck.

Body:
I know how to listen for tab key presses in Elm. And I know how to stop the focus from being changed using onWithOptions:

textarea
    [ onWithOptions "keydown" (Options False True) <| Decode.map KeyDown keyCode ] []

I can then check, in my update function, if the keyCode pressed was a 9, representing a tab. The problem is now the default behavior of a textarea doesn't work. Anything I type doesn't appear in the textarea. Easy enough, I simply add whatever I type to the model and make the value of the textarea the model. Now I have issues with the cursor and, more importantly, clipboard pasting doesn't work...

How do I get tabs to work properly with textareas in Elm? Normally, it would seem to make sense to only call preventDefault() if the tab key was pressed. How can I conditionally call preventDefault() in Elm?

Body:
Elm does support conditional event propagation through a Decoder that either succeeds or fails. Simply map the message type you want to react to in your update function:

succeededIfTabKey : Int -> Decode.Decoder Int
succeededIfTabKey key =
    if key == 9 then
        Decode.succeed key
    else
        Decode.fail "non-tab"

tabPressed : Decode.Decoder Msg
tabPressed =
    Decode.andThen succeededIfTabKey keyCode
        |> Decode.map (always TabPressed)

And then use this as your attribute for your input element:

onWithOptions "keydown" { defaultOptions | preventDefault = True } tabPressed

This isn't ideal for all situations. If you want some keydown events to not preventDefault(), and other keydown events to preventDefault(), then you're out of luck.