问:
Recycleview's onClick and put extra
Please help!  i have a recycleview with search function(base on JSON search). i wanna click-able this recycleview(mean that getting item's ID where shown in item's view ) and then PutExtra this ID to another activity . then another activity get ID. and finally another activity post ID and get values!

this my code , somebody tell my wrongs:):

AdapterFish.java

```<code>public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private Context context;
private LayoutInflater inflater;
List<DataFish> data= Collections.emptyList();
DataFish current;
int currentPos=0;
public String IDHOLDER;
private Context activity;

// create constructor to initialize context and data sent from MainActivity
public AdapterFish(Context context, List<DataFish> data){
    this.context=context;
    inflater= LayoutInflater.from(context);
    this.data=data;
}

// Inflate the layout when ViewHolder created
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view=inflater.inflate(R.layout.container_fish, parent,false);
    MyHolder holder=new MyHolder(view);
    return holder;
}

// Bind data
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    // Get current position of item in RecyclerView to bind data and assign values from list
    MyHolder myHolder= (MyHolder) holder;
    DataFish current=data.get(position);
    myHolder.company.setText(current.company);
    myHolder.name.setText(current.name);
    myHolder.family.setText(current.family);
    myHolder.id.setText(current.id);
    myHolder.id.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

}

// return total item from List
@Override
public int getItemCount() {
    return data.size();
}

public Context getActivity() {
    return activity;
}

public void setActivity(Context activity) {
    this.activity = activity;
}

class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    TextView company;
    TextView name;
    TextView family;
    TextView id;

    // create constructor to get widget reference
    public MyHolder(View itemView) {
        super(itemView);
        company= (TextView) itemView.findViewById(R.id.company);
        name = (TextView) itemView.findViewById(R.id.name);
        family = (TextView) itemView.findViewById(R.id.family);
        id = (TextView) itemView.findViewById(R.id.id);
        itemView.setOnClickListener(this);
    }

    // Click event for all items
    @Override
    public void onClick(View v) {

        Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
        final String ItemId = id.getText().toString().trim();
        Intent intent = new Intent(context, ShowSingleRecordActivity.class);
        intent.putExtra("ID", ItemId);
        context.startActivity(intent);

    }

}}
</code>```

ShowSingleRecordActivity.java (Receiving ID)

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

HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;

// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "http://192.168.137.1/namayeshgah/FilterStudentData.php";

// Http URL for delete Already Open Student Record.
String HttpUrlDeleteRecord = "http://192.168.137.1/namayeshgah/DeleteStudent.php";

String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView COMPANY,NAME,FAMILY,GENDER,EMAIL1,EMAIL2,PHONE,FAX,TELLFAX,MOBILE;
String  CompanyHolder ,NameHolder,FamilyHolder,GenderHolder,Email1Holder,Email2Holder,PhoneHolder,FaxHolder,TellfaxHolder,MobileHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;

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

    COMPANY = (TextView)findViewById(R.id.ncompany);
    NAME = (TextView)findViewById(R.id.nname);
    FAMILY=(TextView)findViewById(R.id.nfamily);
    GENDER =(TextView)findViewById(R.id.ngender);
    EMAIL1= (TextView)findViewById(R.id.nemail1);
    EMAIL2= (TextView)findViewById(R.id.nemail2);
    PHONE= (TextView)findViewById(R.id.nphone);
    FAX = (TextView)findViewById(R.id.nfax);
    TELLFAX = (TextView)findViewById(R.id.ntellfax);
    MOBILE = (TextView)findViewById(R.id.nmobile);

    UpdateButton = (Button)findViewById(R.id.buttonUpdate);
    DeleteButton = (Button)findViewById(R.id.buttonDelete);

    //Receiving the ListView Clicked item value send by previous activity.
    TempItem = getIntent().getStringExtra("ID");

    //Calling method to filter Student Record and open selected record.
    HttpWebCall(TempItem);

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

            Intent intent = new Intent(ShowSingleRecordActivity.this,UpdateActivity.class);

            // Sending Student Id, Name, Number and Class to next UpdateActivity.
            intent.putExtra("Id", TempItem);
            intent.putExtra("company",CompanyHolder );
            intent.putExtra("name", NameHolder);
            intent.putExtra("family",FamilyHolder );
            intent.putExtra("gender",GenderHolder );
            intent.putExtra("email1",Email1Holder );
            intent.putExtra("email2",Email2Holder );
            intent.putExtra("phone",PhoneHolder );
            intent.putExtra("fax",FaxHolder );
            intent.putExtra("tellfax",TellfaxHolder );
            intent.putExtra("mobile",MobileHolder );

            startActivity(intent);

            // Finishing current activity after opening next activity.
            finish();

        }
    });

    // Add Click listener on Delete button.
    DeleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // Calling Student delete method to delete current record using Student ID.
            StudentDelete(TempItem);

        }
    });

}

// Method to Delete Student Record
public void StudentDelete(final String StudentID) {

    class StudentDeleteClass extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog2 = ProgressDialog.show(ShowSingleRecordActivity.this, "Loading Data", null, true, true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            progressDialog2.dismiss();

            Toast.makeText(ShowSingleRecordActivity.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();

            finish();

        }

        @Override
        protected String doInBackground(String... params) {

            // Sending STUDENT id.
            hashMap.put("StudentID", params[0]);

            finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);

            return finalResult;
        }
    }

    StudentDeleteClass studentDeleteClass = new StudentDeleteClass();

    studentDeleteClass.execute(StudentID);
}

//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){

    class HttpWebCallFunction extends AsyncTask<String,Void,String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = ProgressDialog.show(ShowSingleRecordActivity.this,"Loading Data",null,true,true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            pDialog.dismiss();

            //Storing Complete JSon Object into String Variable.
            FinalJSonObject = httpResponseMsg ;

            //Parsing the Stored JSOn String to GetHttpResponse Method.
            new GetHttpResponse(ShowSingleRecordActivity.this).execute();

        }

        @Override
        protected String doInBackground(String... params) {

            ResultHash.put("StudentID",params[0]);

            ParseResult = httpParse.postRequest(ResultHash, HttpURL);

            return ParseResult;
        }
    }

    HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();

    httpWebCallFunction.execute(PreviousListViewClickedItem);
}

// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
    public Context context;

    public GetHttpResponse(Context context)
    {
        this.context = context;
    }

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... arg0)
    {
        try
        {
            if(FinalJSonObject != null)
            {
                JSONArray jsonArray = null;

                try {
                    jsonArray = new JSONArray(FinalJSonObject);

                    JSONObject jsonObject;

                    for(int i=0; i<jsonArray.length(); i++)
                    {
                        jsonObject = jsonArray.getJSONObject(i);

                        // Storing Student Name, Phone Number, Class into Variables.
                        CompanyHolder = jsonObject.getString("company");
                        NameHolder = jsonObject.getString("name");
                        FamilyHolder= jsonObject.getString("family");
                        GenderHolder= jsonObject.getString("gender");
                        Email1Holder = jsonObject.getString("email1");
                        Email2Holder = jsonObject.getString("email2");
                        PhoneHolder = jsonObject.getString("phone");
                        FaxHolder = jsonObject.getString("fax");
                        TellfaxHolder = jsonObject.getString("tellfax");
                        MobileHolder = jsonObject.getString("mobile");

                    }
                }
                catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result)
    {

        // Setting Student Name, Phone Number, Class into TextView after done all process .
        COMPANY.setText(CompanyHolder);
        NAME.setText(NameHolder);
        FAMILY.setText(FamilyHolder);
        GENDER.setText(GenderHolder);
        EMAIL1.setText(Email1Holder);
        EMAIL2.setText(Email2Holder);
        PHONE.setText(PhoneHolder);
        FAX.setText(FaxHolder);
        TELLFAX.setText(TellfaxHolder);
        MOBILE.setText(MobileHolder);

    }
}
</code>```

and Searching.java

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

// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFish;
private AdapterFish mAdapter;

SearchView searchView = null;

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // adds item to action bar
    getMenuInflater().inflate(R.menu.search_main, menu);

    // Get Search item from action bar and Get Search service
    MenuItem searchItem = menu.findItem(R.id.action_search);
    SearchManager searchManager = (SearchManager) searching.this.getSystemService(Context.SEARCH_SERVICE);
    if (searchItem != null) {
        searchView = (SearchView) searchItem.getActionView();
    }
    if (searchView != null) {
        searchView.setSearchableInfo(searchManager.getSearchableInfo(searching.this.getComponentName()));
        searchView.setIconified(false);
    }

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    return super.onOptionsItemSelected(item);
}

// Every time when you press search button on keypad an Activity is recreated which in turn calls this function
@Override
protected void onNewIntent(Intent intent) {
    // Get search query and create object of class AsyncFetch
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        if (searchView != null) {
            searchView.clearFocus();
        }
        new AsyncFetch(query).execute();

    }
}

// Create class AsyncFetch
private class AsyncFetch extends AsyncTask<String, String, String> {

    ProgressDialog pdLoading = new ProgressDialog(searching.this);
    HttpURLConnection conn;
    URL url = null;
    String searchQuery;

    public AsyncFetch(String searchQuery){
        this.searchQuery=searchQuery;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tLoading...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            // Enter URL address where your php file resides
            url = new URL("http://192.168.137.1/namayeshgah/search/fish-search.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {

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

            // setDoInput and setDoOutput to true as we send and recieve data
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // add parameter to our above url
            Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
            String query = builder.build().getEncodedQuery();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

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

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {
                return("Connection error");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }

    }

    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread
        pdLoading.dismiss();
        List<DataFish> data=new ArrayList<>();

        pdLoading.dismiss();
        if(result.equals("no rows")) {
            Toast.makeText(searching.this, "No Results found for entered query", Toast.LENGTH_LONG).show();
        }else{

            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    DataFish fishData = new DataFish();
                    fishData.company = json_data.getString("company");
                    fishData.name = json_data.getString("name");
                    fishData.family = json_data.getString("family");
                    fishData.id = json_data.getString("id");

                    data.add(fishData);
                }

                // Setup and Handover data to recyclerview
                mRVFish = (RecyclerView) findViewById(R.id.fishPriceList);
                mAdapter = new AdapterFish(searching.this, data);
                mRVFish.setAdapter(mAdapter);
                mRVFish.setLayoutManager(new LinearLayoutManager(searching.this));

            } catch (JSONException e) {
                // You to understand what actually error is and handle it appropriately
                Toast.makeText(searching.this, e.toString(), Toast.LENGTH_LONG).show();
                Toast.makeText(searching.this, result.toString(), Toast.LENGTH_LONG).show();
            }

        }

    }

}
</code>```

答:
Try with following code hope so it will be working.

```<code>public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    private LayoutInflater inflater;
    List<DataFish> data= Collections.emptyList();
    DataFish current;
    int currentPos=0;
    public String IDHOLDER;
    private Context activity;

    // create constructor to initialize context and data sent from MainActivity
    public AdapterFish(Context context, List<DataFish> data){
        this.context=context;
        inflater= LayoutInflater.from(context);
        this.data=data;
    }

    // Inflate the layout when ViewHolder created
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view=inflater.inflate(R.layout.container_fish, parent,false);
        MyHolder holder=new MyHolder(view);
        return holder;
    }

    // Bind data
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        // Get current position of item in RecyclerView to bind data and assign values from list
        MyHolder myHolder= (MyHolder) holder;
        DataFish current=data.get(position);
        myHolder.company.setText(current.company);
        myHolder.name.setText(current.name);
        myHolder.family.setText(current.family);
        myHolder.id.setText(current.id);
        myHolder.id.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

        ((MyHolder ) holder).itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                     Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
            //final String ItemId = id.getText().toString().trim();
            Intent intent = new Intent(context, ShowSingleRecordActivity.class);
            intent.putExtra("ID", current.id);
            context.startActivity(intent);
                }
            });

    }

    // return total item from List
    @Override
    public int getItemCount() {
        return data.size();
    }

    public Context getActivity() {
        return activity;
    }

    public void setActivity(Context activity) {
        this.activity = activity;
    }

    class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        TextView company;
        TextView name;
        TextView family;
        TextView id;

        // create constructor to get widget reference
        public MyHolder(View itemView) {
            super(itemView);
            company= (TextView) itemView.findViewById(R.id.company);
            name = (TextView) itemView.findViewById(R.id.name);
            family = (TextView) itemView.findViewById(R.id.family);
            id = (TextView) itemView.findViewById(R.id.id);
            itemView.setOnClickListener(this);
        }

        // Click event for all items
        @Override
        public void onClick(View v) {

              }

    }}
</code>```

ShowSingleRecordActivity.java (Receiving ID)

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

HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;

// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "http://192.168.137.1/namayeshgah/FilterStudentData.php";

// Http URL for delete Already Open Student Record.
String HttpUrlDeleteRecord = "http://192.168.137.1/namayeshgah/DeleteStudent.php";

String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView COMPANY,NAME,FAMILY,GENDER,EMAIL1,EMAIL2,PHONE,FAX,TELLFAX,MOBILE;
String  CompanyHolder ,NameHolder,FamilyHolder,GenderHolder,Email1Holder,Email2Holder,PhoneHolder,FaxHolder,TellfaxHolder,MobileHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;

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

    COMPANY = (TextView)findViewById(R.id.ncompany);
    NAME = (TextView)findViewById(R.id.nname);
    FAMILY=(TextView)findViewById(R.id.nfamily);
    GENDER =(TextView)findViewById(R.id.ngender);
    EMAIL1= (TextView)findViewById(R.id.nemail1);
    EMAIL2= (TextView)findViewById(R.id.nemail2);
    PHONE= (TextView)findViewById(R.id.nphone);
    FAX = (TextView)findViewById(R.id.nfax);
    TELLFAX = (TextView)findViewById(R.id.ntellfax);
    MOBILE = (TextView)findViewById(R.id.nmobile);

    UpdateButton = (Button)findViewById(R.id.buttonUpdate);
    DeleteButton = (Button)findViewById(R.id.buttonDelete);

    //Receiving the ListView Clicked item value send by previous activity.
    TempItem = getIntent().getExtra("ID");
    System.out.println("TempItem=============>"+TempItem )

    //Calling method to filter Student Record and open selected record.
    if(null != TempItem){
     HttpWebCall(TempItem);
    }else{
      Toast.makeText(context, "Item ID is not get from list", Toast.LENGTH_SHORT).show();
    }

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

            Intent intent = new Intent(ShowSingleRecordActivity.this,UpdateActivity.class);

            // Sending Student Id, Name, Number and Class to next UpdateActivity.
            intent.putExtra("Id", TempItem);
            intent.putExtra("company",CompanyHolder );
            intent.putExtra("name", NameHolder);
            intent.putExtra("family",FamilyHolder );
            intent.putExtra("gender",GenderHolder );
            intent.putExtra("email1",Email1Holder );
            intent.putExtra("email2",Email2Holder );
            intent.putExtra("phone",PhoneHolder );
            intent.putExtra("fax",FaxHolder );
            intent.putExtra("tellfax",TellfaxHolder );
            intent.putExtra("mobile",MobileHolder );

            startActivity(intent);

            // Finishing current activity after opening next activity.
            finish();

        }
    });

    // Add Click listener on Delete button.
    DeleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // Calling Student delete method to delete current record using Student ID.
            StudentDelete(TempItem);

        }
    });

}

// Method to Delete Student Record
public void StudentDelete(final String StudentID) {

    class StudentDeleteClass extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog2 = ProgressDialog.show(ShowSingleRecordActivity.this, "Loading Data", null, true, true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            progressDialog2.dismiss();

            Toast.makeText(ShowSingleRecordActivity.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();

            finish();

        }

        @Override
        protected String doInBackground(String... params) {

            // Sending STUDENT id.
            hashMap.put("StudentID", params[0]);

            finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);

            return finalResult;
        }
    }

    StudentDeleteClass studentDeleteClass = new StudentDeleteClass();

    studentDeleteClass.execute(StudentID);
}

//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){

    class HttpWebCallFunction extends AsyncTask<String,Void,String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = ProgressDialog.show(ShowSingleRecordActivity.this,"Loading Data",null,true,true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            pDialog.dismiss();

            //Storing Complete JSon Object into String Variable.
            FinalJSonObject = httpResponseMsg ;

            //Parsing the Stored JSOn String to GetHttpResponse Method.
            new GetHttpResponse(ShowSingleRecordActivity.this).execute();

        }

        @Override
        protected String doInBackground(String... params) {

            ResultHash.put("StudentID",params[0]);

            ParseResult = httpParse.postRequest(ResultHash, HttpURL);

            return ParseResult;
        }
    }

    HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();

    httpWebCallFunction.execute(PreviousListViewClickedItem);
}

// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
    public Context context;

    public GetHttpResponse(Context context)
    {
        this.context = context;
    }

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... arg0)
    {
        try
        {
            if(FinalJSonObject != null)
            {
                JSONArray jsonArray = null;

                try {
                    jsonArray = new JSONArray(FinalJSonObject);

                    JSONObject jsonObject;

                    for(int i=0; i<jsonArray.length(); i++)
                    {
                        jsonObject = jsonArray.getJSONObject(i);

                        // Storing Student Name, Phone Number, Class into Variables.
                        CompanyHolder = jsonObject.getString("company");
                        NameHolder = jsonObject.getString("name");
                        FamilyHolder= jsonObject.getString("family");
                        GenderHolder= jsonObject.getString("gender");
                        Email1Holder = jsonObject.getString("email1");
                        Email2Holder = jsonObject.getString("email2");
                        PhoneHolder = jsonObject.getString("phone");
                        FaxHolder = jsonObject.getString("fax");
                        TellfaxHolder = jsonObject.getString("tellfax");
                        MobileHolder = jsonObject.getString("mobile");

                    }
                }
                catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result)
    {

        // Setting Student Name, Phone Number, Class into TextView after done all process .
        COMPANY.setText(CompanyHolder);
        NAME.setText(NameHolder);
        FAMILY.setText(FamilyHolder);
        GENDER.setText(GenderHolder);
        EMAIL1.setText(Email1Holder);
        EMAIL2.setText(Email2Holder);
        PHONE.setText(PhoneHolder);
        FAX.setText(FaxHolder);
        TELLFAX.setText(TellfaxHolder);
        MOBILE.setText(MobileHolder);

    }
}
</code>```

Title: Recycleview's onClick and put extra

Body:
Please help!  i have a recycleview with search function(base on JSON search). i wanna click-able this recycleview(mean that getting item's ID where shown in item's view ) and then PutExtra this ID to another activity . then another activity get ID. and finally another activity post ID and get values!

this my code , somebody tell my wrongs:):

AdapterFish.java

public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

private Context context;
private LayoutInflater inflater;
List<DataFish> data= Collections.emptyList();
DataFish current;
int currentPos=0;
public String IDHOLDER;
private Context activity;

// create constructor to initialize context and data sent from MainActivity
public AdapterFish(Context context, List<DataFish> data){
    this.context=context;
    inflater= LayoutInflater.from(context);
    this.data=data;
}

// Inflate the layout when ViewHolder created
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view=inflater.inflate(R.layout.container_fish, parent,false);
    MyHolder holder=new MyHolder(view);
    return holder;
}

// Bind data
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    // Get current position of item in RecyclerView to bind data and assign values from list
    MyHolder myHolder= (MyHolder) holder;
    DataFish current=data.get(position);
    myHolder.company.setText(current.company);
    myHolder.name.setText(current.name);
    myHolder.family.setText(current.family);
    myHolder.id.setText(current.id);
    myHolder.id.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

}

// return total item from List
@Override
public int getItemCount() {
    return data.size();
}

public Context getActivity() {
    return activity;
}

public void setActivity(Context activity) {
    this.activity = activity;
}

class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    TextView company;
    TextView name;
    TextView family;
    TextView id;

    // create constructor to get widget reference
    public MyHolder(View itemView) {
        super(itemView);
        company= (TextView) itemView.findViewById(R.id.company);
        name = (TextView) itemView.findViewById(R.id.name);
        family = (TextView) itemView.findViewById(R.id.family);
        id = (TextView) itemView.findViewById(R.id.id);
        itemView.setOnClickListener(this);
    }

    // Click event for all items
    @Override
    public void onClick(View v) {

        Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
        final String ItemId = id.getText().toString().trim();
        Intent intent = new Intent(context, ShowSingleRecordActivity.class);
        intent.putExtra("ID", ItemId);
        context.startActivity(intent);

    }

}}

ShowSingleRecordActivity.java (Receiving ID)

public class ShowSingleRecordActivity extends AppCompatActivity {

HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;

// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "http://192.168.137.1/namayeshgah/FilterStudentData.php";

// Http URL for delete Already Open Student Record.
String HttpUrlDeleteRecord = "http://192.168.137.1/namayeshgah/DeleteStudent.php";

String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView COMPANY,NAME,FAMILY,GENDER,EMAIL1,EMAIL2,PHONE,FAX,TELLFAX,MOBILE;
String  CompanyHolder ,NameHolder,FamilyHolder,GenderHolder,Email1Holder,Email2Holder,PhoneHolder,FaxHolder,TellfaxHolder,MobileHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;

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

    COMPANY = (TextView)findViewById(R.id.ncompany);
    NAME = (TextView)findViewById(R.id.nname);
    FAMILY=(TextView)findViewById(R.id.nfamily);
    GENDER =(TextView)findViewById(R.id.ngender);
    EMAIL1= (TextView)findViewById(R.id.nemail1);
    EMAIL2= (TextView)findViewById(R.id.nemail2);
    PHONE= (TextView)findViewById(R.id.nphone);
    FAX = (TextView)findViewById(R.id.nfax);
    TELLFAX = (TextView)findViewById(R.id.ntellfax);
    MOBILE = (TextView)findViewById(R.id.nmobile);

    UpdateButton = (Button)findViewById(R.id.buttonUpdate);
    DeleteButton = (Button)findViewById(R.id.buttonDelete);

    //Receiving the ListView Clicked item value send by previous activity.
    TempItem = getIntent().getStringExtra("ID");

    //Calling method to filter Student Record and open selected record.
    HttpWebCall(TempItem);

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

            Intent intent = new Intent(ShowSingleRecordActivity.this,UpdateActivity.class);

            // Sending Student Id, Name, Number and Class to next UpdateActivity.
            intent.putExtra("Id", TempItem);
            intent.putExtra("company",CompanyHolder );
            intent.putExtra("name", NameHolder);
            intent.putExtra("family",FamilyHolder );
            intent.putExtra("gender",GenderHolder );
            intent.putExtra("email1",Email1Holder );
            intent.putExtra("email2",Email2Holder );
            intent.putExtra("phone",PhoneHolder );
            intent.putExtra("fax",FaxHolder );
            intent.putExtra("tellfax",TellfaxHolder );
            intent.putExtra("mobile",MobileHolder );

            startActivity(intent);

            // Finishing current activity after opening next activity.
            finish();

        }
    });

    // Add Click listener on Delete button.
    DeleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // Calling Student delete method to delete current record using Student ID.
            StudentDelete(TempItem);

        }
    });

}

// Method to Delete Student Record
public void StudentDelete(final String StudentID) {

    class StudentDeleteClass extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog2 = ProgressDialog.show(ShowSingleRecordActivity.this, "Loading Data", null, true, true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            progressDialog2.dismiss();

            Toast.makeText(ShowSingleRecordActivity.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();

            finish();

        }

        @Override
        protected String doInBackground(String... params) {

            // Sending STUDENT id.
            hashMap.put("StudentID", params[0]);

            finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);

            return finalResult;
        }
    }

    StudentDeleteClass studentDeleteClass = new StudentDeleteClass();

    studentDeleteClass.execute(StudentID);
}

//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){

    class HttpWebCallFunction extends AsyncTask<String,Void,String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = ProgressDialog.show(ShowSingleRecordActivity.this,"Loading Data",null,true,true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            pDialog.dismiss();

            //Storing Complete JSon Object into String Variable.
            FinalJSonObject = httpResponseMsg ;

            //Parsing the Stored JSOn String to GetHttpResponse Method.
            new GetHttpResponse(ShowSingleRecordActivity.this).execute();

        }

        @Override
        protected String doInBackground(String... params) {

            ResultHash.put("StudentID",params[0]);

            ParseResult = httpParse.postRequest(ResultHash, HttpURL);

            return ParseResult;
        }
    }

    HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();

    httpWebCallFunction.execute(PreviousListViewClickedItem);
}

// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
    public Context context;

    public GetHttpResponse(Context context)
    {
        this.context = context;
    }

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... arg0)
    {
        try
        {
            if(FinalJSonObject != null)
            {
                JSONArray jsonArray = null;

                try {
                    jsonArray = new JSONArray(FinalJSonObject);

                    JSONObject jsonObject;

                    for(int i=0; i<jsonArray.length(); i++)
                    {
                        jsonObject = jsonArray.getJSONObject(i);

                        // Storing Student Name, Phone Number, Class into Variables.
                        CompanyHolder = jsonObject.getString("company");
                        NameHolder = jsonObject.getString("name");
                        FamilyHolder= jsonObject.getString("family");
                        GenderHolder= jsonObject.getString("gender");
                        Email1Holder = jsonObject.getString("email1");
                        Email2Holder = jsonObject.getString("email2");
                        PhoneHolder = jsonObject.getString("phone");
                        FaxHolder = jsonObject.getString("fax");
                        TellfaxHolder = jsonObject.getString("tellfax");
                        MobileHolder = jsonObject.getString("mobile");

                    }
                }
                catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result)
    {

        // Setting Student Name, Phone Number, Class into TextView after done all process .
        COMPANY.setText(CompanyHolder);
        NAME.setText(NameHolder);
        FAMILY.setText(FamilyHolder);
        GENDER.setText(GenderHolder);
        EMAIL1.setText(Email1Holder);
        EMAIL2.setText(Email2Holder);
        PHONE.setText(PhoneHolder);
        FAX.setText(FaxHolder);
        TELLFAX.setText(TellfaxHolder);
        MOBILE.setText(MobileHolder);

    }
}

and Searching.java

public class searching extends AppCompatActivity {

// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFish;
private AdapterFish mAdapter;

SearchView searchView = null;

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // adds item to action bar
    getMenuInflater().inflate(R.menu.search_main, menu);

    // Get Search item from action bar and Get Search service
    MenuItem searchItem = menu.findItem(R.id.action_search);
    SearchManager searchManager = (SearchManager) searching.this.getSystemService(Context.SEARCH_SERVICE);
    if (searchItem != null) {
        searchView = (SearchView) searchItem.getActionView();
    }
    if (searchView != null) {
        searchView.setSearchableInfo(searchManager.getSearchableInfo(searching.this.getComponentName()));
        searchView.setIconified(false);
    }

    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    return super.onOptionsItemSelected(item);
}

// Every time when you press search button on keypad an Activity is recreated which in turn calls this function
@Override
protected void onNewIntent(Intent intent) {
    // Get search query and create object of class AsyncFetch
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = intent.getStringExtra(SearchManager.QUERY);
        if (searchView != null) {
            searchView.clearFocus();
        }
        new AsyncFetch(query).execute();

    }
}

// Create class AsyncFetch
private class AsyncFetch extends AsyncTask<String, String, String> {

    ProgressDialog pdLoading = new ProgressDialog(searching.this);
    HttpURLConnection conn;
    URL url = null;
    String searchQuery;

    public AsyncFetch(String searchQuery){
        this.searchQuery=searchQuery;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        //this method will be running on UI thread
        pdLoading.setMessage("\tLoading...");
        pdLoading.setCancelable(false);
        pdLoading.show();

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            // Enter URL address where your php file resides
            url = new URL("http://192.168.137.1/namayeshgah/search/fish-search.php");

        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return e.toString();
        }
        try {

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

            // setDoInput and setDoOutput to true as we send and recieve data
            conn.setDoInput(true);
            conn.setDoOutput(true);

            // add parameter to our above url
            Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
            String query = builder.build().getEncodedQuery();

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();
            conn.connect();

        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            return e1.toString();
        }

        try {

            int response_code = conn.getResponseCode();

            // Check if successful connection made
            if (response_code == HttpURLConnection.HTTP_OK) {

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

                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                // Pass data to onPostExecute method
                return (result.toString());

            } else {
                return("Connection error");
            }

        } catch (IOException e) {
            e.printStackTrace();
            return e.toString();
        } finally {
            conn.disconnect();
        }

    }

    @Override
    protected void onPostExecute(String result) {

        //this method will be running on UI thread
        pdLoading.dismiss();
        List<DataFish> data=new ArrayList<>();

        pdLoading.dismiss();
        if(result.equals("no rows")) {
            Toast.makeText(searching.this, "No Results found for entered query", Toast.LENGTH_LONG).show();
        }else{

            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for (int i = 0; i < jArray.length(); i++) {
                    JSONObject json_data = jArray.getJSONObject(i);
                    DataFish fishData = new DataFish();
                    fishData.company = json_data.getString("company");
                    fishData.name = json_data.getString("name");
                    fishData.family = json_data.getString("family");
                    fishData.id = json_data.getString("id");

                    data.add(fishData);
                }

                // Setup and Handover data to recyclerview
                mRVFish = (RecyclerView) findViewById(R.id.fishPriceList);
                mAdapter = new AdapterFish(searching.this, data);
                mRVFish.setAdapter(mAdapter);
                mRVFish.setLayoutManager(new LinearLayoutManager(searching.this));

            } catch (JSONException e) {
                // You to understand what actually error is and handle it appropriately
                Toast.makeText(searching.this, e.toString(), Toast.LENGTH_LONG).show();
                Toast.makeText(searching.this, result.toString(), Toast.LENGTH_LONG).show();
            }

        }

    }

}

Body:
Try with following code hope so it will be working.

public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    private LayoutInflater inflater;
    List<DataFish> data= Collections.emptyList();
    DataFish current;
    int currentPos=0;
    public String IDHOLDER;
    private Context activity;

    // create constructor to initialize context and data sent from MainActivity
    public AdapterFish(Context context, List<DataFish> data){
        this.context=context;
        inflater= LayoutInflater.from(context);
        this.data=data;
    }

    // Inflate the layout when ViewHolder created
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view=inflater.inflate(R.layout.container_fish, parent,false);
        MyHolder holder=new MyHolder(view);
        return holder;
    }

    // Bind data
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        // Get current position of item in RecyclerView to bind data and assign values from list
        MyHolder myHolder= (MyHolder) holder;
        DataFish current=data.get(position);
        myHolder.company.setText(current.company);
        myHolder.name.setText(current.name);
        myHolder.family.setText(current.family);
        myHolder.id.setText(current.id);
        myHolder.id.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

        ((MyHolder ) holder).itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                     Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
            //final String ItemId = id.getText().toString().trim();
            Intent intent = new Intent(context, ShowSingleRecordActivity.class);
            intent.putExtra("ID", current.id);
            context.startActivity(intent);
                }
            });

    }

    // return total item from List
    @Override
    public int getItemCount() {
        return data.size();
    }

    public Context getActivity() {
        return activity;
    }

    public void setActivity(Context activity) {
        this.activity = activity;
    }

    class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        TextView company;
        TextView name;
        TextView family;
        TextView id;

        // create constructor to get widget reference
        public MyHolder(View itemView) {
            super(itemView);
            company= (TextView) itemView.findViewById(R.id.company);
            name = (TextView) itemView.findViewById(R.id.name);
            family = (TextView) itemView.findViewById(R.id.family);
            id = (TextView) itemView.findViewById(R.id.id);
            itemView.setOnClickListener(this);
        }

        // Click event for all items
        @Override
        public void onClick(View v) {

              }

    }}

ShowSingleRecordActivity.java (Receiving ID)

public class ShowSingleRecordActivity extends AppCompatActivity {

HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;

// Http Url For Filter Student Data from Id Sent from previous activity.
String HttpURL = "http://192.168.137.1/namayeshgah/FilterStudentData.php";

// Http URL for delete Already Open Student Record.
String HttpUrlDeleteRecord = "http://192.168.137.1/namayeshgah/DeleteStudent.php";

String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
TextView COMPANY,NAME,FAMILY,GENDER,EMAIL1,EMAIL2,PHONE,FAX,TELLFAX,MOBILE;
String  CompanyHolder ,NameHolder,FamilyHolder,GenderHolder,Email1Holder,Email2Holder,PhoneHolder,FaxHolder,TellfaxHolder,MobileHolder;
Button UpdateButton, DeleteButton;
String TempItem;
ProgressDialog progressDialog2;

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

    COMPANY = (TextView)findViewById(R.id.ncompany);
    NAME = (TextView)findViewById(R.id.nname);
    FAMILY=(TextView)findViewById(R.id.nfamily);
    GENDER =(TextView)findViewById(R.id.ngender);
    EMAIL1= (TextView)findViewById(R.id.nemail1);
    EMAIL2= (TextView)findViewById(R.id.nemail2);
    PHONE= (TextView)findViewById(R.id.nphone);
    FAX = (TextView)findViewById(R.id.nfax);
    TELLFAX = (TextView)findViewById(R.id.ntellfax);
    MOBILE = (TextView)findViewById(R.id.nmobile);

    UpdateButton = (Button)findViewById(R.id.buttonUpdate);
    DeleteButton = (Button)findViewById(R.id.buttonDelete);

    //Receiving the ListView Clicked item value send by previous activity.
    TempItem = getIntent().getExtra("ID");
    System.out.println("TempItem=============>"+TempItem )

    //Calling method to filter Student Record and open selected record.
    if(null != TempItem){
     HttpWebCall(TempItem);
    }else{
      Toast.makeText(context, "Item ID is not get from list", Toast.LENGTH_SHORT).show();
    }

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

            Intent intent = new Intent(ShowSingleRecordActivity.this,UpdateActivity.class);

            // Sending Student Id, Name, Number and Class to next UpdateActivity.
            intent.putExtra("Id", TempItem);
            intent.putExtra("company",CompanyHolder );
            intent.putExtra("name", NameHolder);
            intent.putExtra("family",FamilyHolder );
            intent.putExtra("gender",GenderHolder );
            intent.putExtra("email1",Email1Holder );
            intent.putExtra("email2",Email2Holder );
            intent.putExtra("phone",PhoneHolder );
            intent.putExtra("fax",FaxHolder );
            intent.putExtra("tellfax",TellfaxHolder );
            intent.putExtra("mobile",MobileHolder );

            startActivity(intent);

            // Finishing current activity after opening next activity.
            finish();

        }
    });

    // Add Click listener on Delete button.
    DeleteButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            // Calling Student delete method to delete current record using Student ID.
            StudentDelete(TempItem);

        }
    });

}

// Method to Delete Student Record
public void StudentDelete(final String StudentID) {

    class StudentDeleteClass extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            progressDialog2 = ProgressDialog.show(ShowSingleRecordActivity.this, "Loading Data", null, true, true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            progressDialog2.dismiss();

            Toast.makeText(ShowSingleRecordActivity.this, httpResponseMsg.toString(), Toast.LENGTH_LONG).show();

            finish();

        }

        @Override
        protected String doInBackground(String... params) {

            // Sending STUDENT id.
            hashMap.put("StudentID", params[0]);

            finalResult = httpParse.postRequest(hashMap, HttpUrlDeleteRecord);

            return finalResult;
        }
    }

    StudentDeleteClass studentDeleteClass = new StudentDeleteClass();

    studentDeleteClass.execute(StudentID);
}

//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){

    class HttpWebCallFunction extends AsyncTask<String,Void,String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = ProgressDialog.show(ShowSingleRecordActivity.this,"Loading Data",null,true,true);
        }

        @Override
        protected void onPostExecute(String httpResponseMsg) {

            super.onPostExecute(httpResponseMsg);

            pDialog.dismiss();

            //Storing Complete JSon Object into String Variable.
            FinalJSonObject = httpResponseMsg ;

            //Parsing the Stored JSOn String to GetHttpResponse Method.
            new GetHttpResponse(ShowSingleRecordActivity.this).execute();

        }

        @Override
        protected String doInBackground(String... params) {

            ResultHash.put("StudentID",params[0]);

            ParseResult = httpParse.postRequest(ResultHash, HttpURL);

            return ParseResult;
        }
    }

    HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();

    httpWebCallFunction.execute(PreviousListViewClickedItem);
}

// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
    public Context context;

    public GetHttpResponse(Context context)
    {
        this.context = context;
    }

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... arg0)
    {
        try
        {
            if(FinalJSonObject != null)
            {
                JSONArray jsonArray = null;

                try {
                    jsonArray = new JSONArray(FinalJSonObject);

                    JSONObject jsonObject;

                    for(int i=0; i<jsonArray.length(); i++)
                    {
                        jsonObject = jsonArray.getJSONObject(i);

                        // Storing Student Name, Phone Number, Class into Variables.
                        CompanyHolder = jsonObject.getString("company");
                        NameHolder = jsonObject.getString("name");
                        FamilyHolder= jsonObject.getString("family");
                        GenderHolder= jsonObject.getString("gender");
                        Email1Holder = jsonObject.getString("email1");
                        Email2Holder = jsonObject.getString("email2");
                        PhoneHolder = jsonObject.getString("phone");
                        FaxHolder = jsonObject.getString("fax");
                        TellfaxHolder = jsonObject.getString("tellfax");
                        MobileHolder = jsonObject.getString("mobile");

                    }
                }
                catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result)
    {

        // Setting Student Name, Phone Number, Class into TextView after done all process .
        COMPANY.setText(CompanyHolder);
        NAME.setText(NameHolder);
        FAMILY.setText(FamilyHolder);
        GENDER.setText(GenderHolder);
        EMAIL1.setText(Email1Holder);
        EMAIL2.setText(Email2Holder);
        PHONE.setText(PhoneHolder);
        FAX.setText(FaxHolder);
        TELLFAX.setText(TellfaxHolder);
        MOBILE.setText(MobileHolder);

    }
}


来源: stackexchange

问:
get one method variable to other method in the same class and show in the route - Laravel 5.2
I have a controller. There have two function. Now i want to get variable(It is random string) value from one function to another function and print this value into the Route(url).

Controller:

```<code>class PrizeCalculateController extends Controller
{
      public function calculatePrize($id, $randomStr=0)
    {
        $randomStr = str_random(5);
        return view('pages.pageWaiting', ['res' => $res, 'randomStr' => $randomStr]);
    }

    public function showPrizePage($id, $randomStr=0)
    {
        //get random string from calculatePrize function
        $getStr = PrizeCalculateController::calculatePrize($randomStr);
        return view('pages.prizesDetails', ['res' => $id, 'getStr' => $getStr]);
    }
}
</code>```

I have tried to get random string from calculatePrize function to showPrizePage function this way:

```<code>$getStr = PrizeCalculateController::calculatePrize($randomStr);
</code>```

And if i dd($getStr) then i get null. Now how can i get this variable from calculatePrize function to showPrizePage function.

Want to make route:

```<code>Route::get('/prize/{getStr}','PrizeCalculateController@showPrizePage');
</code>```

答:
```<code>// Use constructor.
class PrizeCalculateController extends Controller
{
        private $random_str;
        public function __construct()
        {
            $this->random_str      =  str_random(5);
        }
          public function calculatePrize($id, $randomStr=0)
        {
            $randomStr = $this->random_str;
            return view('pages.pageWaiting', ['res' => $res, 'randomStr' => $randomStr]);
        }

        public function showPrizePage($id, $randomStr=0)
        {
            //get random string from calculatePrize function
            $getStr = PrizeCalculateController::calculatePrize($this->random_str);
            return view('pages.prizesDetails', ['res' => $id, 'getStr' => $getStr]);
        }
}
</code>```

Try this hope it helps you. Let me know if any problem.

ContentLicense: CC BY-SA 3.0

Body:
I have a controller. There have two function. Now i want to get variable(It is random string) value from one function to another function and print this value into the Route(url).

Controller:

class PrizeCalculateController extends Controller
{
      public function calculatePrize($id, $randomStr=0)
    {
        $randomStr = str_random(5);
        return view('pages.pageWaiting', ['res' => $res, 'randomStr' => $randomStr]);
    }

    public function showPrizePage($id, $randomStr=0)
    {
        //get random string from calculatePrize function
        $getStr = PrizeCalculateController::calculatePrize($randomStr);
        return view('pages.prizesDetails', ['res' => $id, 'getStr' => $getStr]);
    }
}

I have tried to get random string from calculatePrize function to showPrizePage function this way:

$getStr = PrizeCalculateController::calculatePrize($randomStr);

And if i dd($getStr) then i get null. Now how can i get this variable from calculatePrize function to showPrizePage function.

Want to make route:

Route::get('/prize/{getStr}','PrizeCalculateController@showPrizePage');

Body:
// Use constructor.
class PrizeCalculateController extends Controller
{
        private $random_str;
        public function __construct()
        {
            $this->random_str      =  str_random(5);
        }
          public function calculatePrize($id, $randomStr=0)
        {
            $randomStr = $this->random_str;
            return view('pages.pageWaiting', ['res' => $res, 'randomStr' => $randomStr]);
        }

        public function showPrizePage($id, $randomStr=0)
        {
            //get random string from calculatePrize function
            $getStr = PrizeCalculateController::calculatePrize($this->random_str);
            return view('pages.prizesDetails', ['res' => $id, 'getStr' => $getStr]);
        }
}

Try this hope it helps you. Let me know if any problem.


问:
Unable to create snmpv3 session and send snmpv3 trap
1. Not able to create SNMPv3 session

I am using NET::SNMP perl library to send snmpv3 trap.It was working fine with snmpv1 and snmpv2 but i am unable to send snmpv3 trap. I am using Mg-soft trap ringer for receiving traps but i am unable to even create a session.

Code for snmpv3 session creation:

```<code>my ($session, $error) = Net::SNMP->session(
-hostname     => 'my_host_name',
-version     => '3',
-username     => 'user-md5',
-authprotocol => 'md5',
-authpassword => 'abcd1234'
);
</code>```

Here the username is the security user name added in Mg-soft trap ringer. Why am i not able to create session.Or please suggest me how can i receive snmpv3 trap sent through NET::SNMP library.

2. Not able to send SNMPv3 trap

I am able to create session for snmpv3 with some trap receiver snmp server configuration i found somewhere. But while sending trap using NET::SNMP library  i am getting following error:

Must be an authoritative SNMP engine to generate a SNMPv2-Trap-PDUdf

Here is the code snippet i used:

```<code>my $OID_sysContact = '1.5.2.9.4.6.6.5.4';
my $result = $session->snmpv2_trap(
-varbindlist => [ $OID_sysContact, OCTET_STRING, 'Help Desk x911' ],
);
</code>```

Please suggest me why am i getting this error.

答:
I see a few missing fields from your snippet as far SNMPv3 is concerned.

I doubt why Net::SNMP does not have the security level field for v3 connections. There are three levels of security - noAuthnoPriv , authNoPriv and authPriv. Based on the these levels, an SNMPv3 connection request can be formed.

Firstly, in your connection request, you only have authentication related information and nothing about the privacy protocol/privacy key. Second, I suggest you to use version value as snmpv3 instead of just 3.

For the trap part, it seems like the sender must be an authoritative SNMP engine - not yet supported by Net::SNMP module. Quoted below from Net::SNMP

snmpv2_trap() - send a SNMP snmpV2-trap to the remote manager

  NOTE: This method can only be used when the version of the object is
  set to SNMPv2c. SNMPv2-Trap-PDUs are supported by SNMPv3, but require
  the sender of the message to be an authoritative SNMP engine which is
  not currently supported by the Net::SNMP module.

Body:
1. Not able to create SNMPv3 session

I am using NET::SNMP perl library to send snmpv3 trap.It was working fine with snmpv1 and snmpv2 but i am unable to send snmpv3 trap. I am using Mg-soft trap ringer for receiving traps but i am unable to even create a session.

Code for snmpv3 session creation:

my ($session, $error) = Net::SNMP->session(
-hostname     => 'my_host_name',
-version     => '3',
-username     => 'user-md5',
-authprotocol => 'md5',
-authpassword => 'abcd1234'
);

Here the username is the security user name added in Mg-soft trap ringer. Why am i not able to create session.Or please suggest me how can i receive snmpv3 trap sent through NET::SNMP library.

2. Not able to send SNMPv3 trap

I am able to create session for snmpv3 with some trap receiver snmp server configuration i found somewhere. But while sending trap using NET::SNMP library  i am getting following error:

Must be an authoritative SNMP engine to generate a SNMPv2-Trap-PDUdf

Here is the code snippet i used:

my $OID_sysContact = '1.5.2.9.4.6.6.5.4';
my $result = $session->snmpv2_trap(
-varbindlist => [ $OID_sysContact, OCTET_STRING, 'Help Desk x911' ],
);

Please suggest me why am i getting this error.


问:
How to change color of button when clicked in WP7?
In WP7 whenever a button is clicked ,the background of button becomes white showing that button is clicked and becomes normal on releasing the mouse button.But I want to change the color of button selection from white to orange.How can i dot it?</p>

答:
You are going to have to play with Visual States of that Button control. Following is the default style for Button extracted from Expression Blend:

```<code><Style x:Key="ButtonStyle1" TargetType="Button">
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="BorderBrush" Value="{StaticResource PhoneForegroundBrush}"/>
    <Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
    <Setter Property="BorderThickness" Value="{StaticResource PhoneBorderThickness}"/>
    <Setter Property="FontFamily" Value="{StaticResource PhoneFontFamilySemiBold}"/>
    <Setter Property="FontSize" Value="{StaticResource PhoneFontSizeMediumLarge}"/>
    <Setter Property="Padding" Value="10,3,10,5"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Grid Background="Transparent">
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal"/>
                            <VisualState x:Name="MouseOver"/>
                            <VisualState x:Name="Pressed">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentContainer">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneBackgroundBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonBackground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneForegroundBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ButtonBackground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneForegroundBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Disabled">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentContainer">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ButtonBackground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonBackground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                    <Border x:Name="ButtonBackground" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" CornerRadius="0" Margin="{StaticResource PhoneTouchTargetOverhang}">
                        <ContentControl x:Name="ContentContainer" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" Padding="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Border>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
</code>```

You will need to change the Pressed visual state to:

(In this case background is changed to Red when the button is pressed)

```<code><VisualState x:Name="Pressed">
    <Storyboard>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentContainer">
            <DiscreteObjectKeyFrame KeyTime="0" Value="Red"/>
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonBackground">
            <DiscreteObjectKeyFrame KeyTime="0" Value="Red"/>
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ButtonBackground">
            <DiscreteObjectKeyFrame KeyTime="0" Value="Red"/>
        </ObjectAnimationUsingKeyFrames>
    </Storyboard>
</VisualState>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You are going to have to play with Visual States of that Button control. Following is the default style for Button extracted from Expression Blend:

<Style x:Key="ButtonStyle1" TargetType="Button">
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="BorderBrush" Value="{StaticResource PhoneForegroundBrush}"/>
    <Setter Property="Foreground" Value="{StaticResource PhoneForegroundBrush}"/>
    <Setter Property="BorderThickness" Value="{StaticResource PhoneBorderThickness}"/>
    <Setter Property="FontFamily" Value="{StaticResource PhoneFontFamilySemiBold}"/>
    <Setter Property="FontSize" Value="{StaticResource PhoneFontSizeMediumLarge}"/>
    <Setter Property="Padding" Value="10,3,10,5"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Grid Background="Transparent">
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="Normal"/>
                            <VisualState x:Name="MouseOver"/>
                            <VisualState x:Name="Pressed">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentContainer">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneBackgroundBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonBackground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneForegroundBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ButtonBackground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneForegroundBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                            <VisualState x:Name="Disabled">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentContainer">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ButtonBackground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneDisabledBrush}"/>
                                    </ObjectAnimationUsingKeyFrames>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonBackground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="Transparent"/>
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                    <Border x:Name="ButtonBackground" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" CornerRadius="0" Margin="{StaticResource PhoneTouchTargetOverhang}">
                        <ContentControl x:Name="ContentContainer" ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" Foreground="{TemplateBinding Foreground}" HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}" Padding="{TemplateBinding Padding}" VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Border>
                </Grid>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

You will need to change the Pressed visual state to:

(In this case background is changed to Red when the button is pressed)

<VisualState x:Name="Pressed">
    <Storyboard>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentContainer">
            <DiscreteObjectKeyFrame KeyTime="0" Value="Red"/>
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="ButtonBackground">
            <DiscreteObjectKeyFrame KeyTime="0" Value="Red"/>
        </ObjectAnimationUsingKeyFrames>
        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="BorderBrush" Storyboard.TargetName="ButtonBackground">
            <DiscreteObjectKeyFrame KeyTime="0" Value="Red"/>
        </ObjectAnimationUsingKeyFrames>
    </Storyboard>
</VisualState>


问:
react-bootstrap navbar not rendering correctly
I'm trying to make a navbar using react-bootstrap, but when I render it I get this:

I'm not getting any error messages, and I can't find any documentation explaining what I've got, but clearly I'm doing something wrong. Any ideas?

This is the code I'm using:

```<code>import React from 'react';
import { Navbar, Nav, NavItem } from 'react-bootstrap/lib/';

const Toolbar = () => {
  return (
    <Navbar staticTop collapseOnSelect>
      <Navbar.Header>
        <Navbar.Brand>
          <a href="test">Brandname Goes Here</a>
        </Navbar.Brand>
        <Navbar.Toggle />
      </Navbar.Header>
      <Navbar.Collapse>
        <Nav>
          <NavItem eventKey={1}>Contact Us</NavItem>
          <NavItem eventKey={2}>About Us</NavItem>
        </Nav>
      </Navbar.Collapse>
    </Navbar>
  )
}

export default Toolbar;
</code>```

答:
It is clear that you haven't imported bootstrap.min.css. Import it in your index.html as follows.

```<code><link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"
integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS"
crossorigin="anonymous"
/>
</code>```

I cannot recommend to use something like import 'react-bootstrap/*/*.css' because I am not sure which framework and which loaders(eg: webpack) you are using.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to make a navbar using react-bootstrap, but when I render it I get this:

I'm not getting any error messages, and I can't find any documentation explaining what I've got, but clearly I'm doing something wrong. Any ideas?

This is the code I'm using:

import React from 'react';
import { Navbar, Nav, NavItem } from 'react-bootstrap/lib/';

const Toolbar = () => {
  return (
    <Navbar staticTop collapseOnSelect>
      <Navbar.Header>
        <Navbar.Brand>
          Brandname Goes Here
        </Navbar.Brand>
        <Navbar.Toggle />
      </Navbar.Header>
      <Navbar.Collapse>

          <NavItem eventKey={1}>Contact Us</NavItem>
          <NavItem eventKey={2}>About Us</NavItem>

      </Navbar.Collapse>
    </Navbar>
  )
}

export default Toolbar;

Body:
It is clear that you haven't imported bootstrap.min.css. Import it in your index.html as follows.

<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"
integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS"
crossorigin="anonymous"
/>

I cannot recommend to use something like import 'react-bootstrap/*/*.css' because I am not sure which framework and which loaders(eg: webpack) you are using.


问:
How to pick every 10 lines from a txt file using python?
I need to write a code where I have huge 7000+ lines of text file. I need to split every 10lines and write it to another file.  </p>

答:
Open the files, then iterate through the input lines writing every 10th line to the output file:

```<code>with open(in_name, 'r') as f:
    with open(out_name, 'w') as g:
        count = 0
        for line in f:
            if count % 10 == 0:
                g.write(line)
            count += 1
</code>```

The open() context manager will close the files when the scope is exited.

Since the decision to output is simply counting you could use a slice f.readlines()[::10]
although if the file is big the itertools islice generator might be more apropriate.

```<code>from itertools import islice

with open(in_name, 'r') as f:
    with open(out_name, 'w') as g:
        g.writelines( islice(f, 0, None, 10) ):
</code>```

I read your question as wanting to write every 10th line. If you want to write lots of files containing 10 chunks of the file you'll need to loop until the input file is exhausted. This is not the same as the question that is shown as a duplicate. That answer breaks if the chunking reads past the end of the file.

```<code>from itertools import islice, count

out_name = 'chunk_{}.txt'

with open(in_name) as f:
    for c in count():
        chunk = list(islice(f, 10))
        if not chunk:
            break
        with open(out_name.format(c)) as g:
            g.writelines(chunk)
</code>```

Body:
Open the files, then iterate through the input lines writing every 10th line to the output file:

with open(in_name, 'r') as f:
    with open(out_name, 'w') as g:
        count = 0
        for line in f:
            if count % 10 == 0:
                g.write(line)
            count += 1

The open() context manager will close the files when the scope is exited.

Since the decision to output is simply counting you could use a slice f.readlines()[::10]
although if the file is big the itertools islice generator might be more apropriate.

from itertools import islice

with open(in_name, 'r') as f:
    with open(out_name, 'w') as g:
        g.writelines( islice(f, 0, None, 10) ):

I read your question as wanting to write every 10th line. If you want to write lots of files containing 10 chunks of the file you'll need to loop until the input file is exhausted. This is not the same as the question that is shown as a duplicate. That answer breaks if the chunking reads past the end of the file.

from itertools import islice, count

out_name = 'chunk_{}.txt'

with open(in_name) as f:
    for c in count():
        chunk = list(islice(f, 10))
        if not chunk:
            break
        with open(out_name.format(c)) as g:
            g.writelines(chunk)


问:
How to stop rethink database call if cannot find result?
I run RethinkDB command with Node.js (babel) asynchronous call:

```<code>let user = await r.table('users').filter({key: key}).limit(1).run();
</code>```

How can I stop the asynchronous call, if database cannot find result?

答:
Using the await function means that node will wait for the asynchronous r.table(... command to return before continuing to the next line of code, meaning that it behaves logically as if it were synchronous code.

Your specific command should return when RethinkDB finds the first 'user' document with the specified key. There is no need to "stop" it if it cannot find a result, it will stop as soon as it (a) finds a result or (b) finished scanning the entire table.

In general "stopping" asynchronous code in node/javascript is not possible but you can limit the amount of time you'll wait for an async method. Here is an example using the Promise.race() function.

```<code>/*
 * toy async function
 *
 * returns a promise that resolves to the specified number `n`
 * after the specified number of seconds `s` (default 2)
 */
const later = (n, s=2) => {
    return new Promise(resolve => {
        setTimeout(() => resolve(n), s*1000);
    })
}

/*
 * returns a promise that rejects with `TIMEOUT_ERROR` after the
 * specified number of seconds `s`
 */
const timeout = (s) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => reject("TIMEOUT_ERROR"), s*1000)
    })
}

/*
 * Example 1: later finished before timeout
 * later resolves after 1 second, timeout function rejects after 3 seconds
 * so we end up in the `.then` block with `val == 42`
 */
Promise.race([later(42, 1), timeout(3)])
    .then(val => {
        // do somethign with val...
        console.log(val)
    }).catch(err => {
        if (err === "TIMEOUT_ERROR") {
            console.log("we timed out!")
        } else {
            consle.log("something failed (but it was not a timeout)")
        }
    });

/*
 * Example 2 (using async/await syntax): we timeout before later returns.
 * later resolves after 3 seconds, timeout function rejects after 2 seconds
 * so we end up in the `.catch` block with `err == "TIMEOUT_ERROR"`
 */
try {
    const val = await Promise.race([later(11, 3), timeout(2)]);
    // do something with val...
} catch (err) {
    if (err === "TIMEOUT_ERROR") {
        console.error("we timed out!")
    } else {
        console.error("something failed (but it was not a timeout)")
    }
}
</code>```

Body:
I run RethinkDB command with Node.js (babel) asynchronous call:

let user = await r.table('users').filter({key: key}).limit(1).run();

How can I stop the asynchronous call, if database cannot find result?

Body:
Using the await function means that node will wait for the asynchronous r.table(... command to return before continuing to the next line of code, meaning that it behaves logically as if it were synchronous code.

Your specific command should return when RethinkDB finds the first 'user' document with the specified key. There is no need to "stop" it if it cannot find a result, it will stop as soon as it (a) finds a result or (b) finished scanning the entire table.

In general "stopping" asynchronous code in node/javascript is not possible but you can limit the amount of time you'll wait for an async method. Here is an example using the Promise.race() function.

/*
 * toy async function
 *
 * returns a promise that resolves to the specified number `n`
 * after the specified number of seconds `s` (default 2)
 */
const later = (n, s=2) => {
    return new Promise(resolve => {
        setTimeout(() => resolve(n), s*1000);
    })
}

/*
 * returns a promise that rejects with `TIMEOUT_ERROR` after the
 * specified number of seconds `s`
 */
const timeout = (s) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => reject("TIMEOUT_ERROR"), s*1000)
    })
}

/*
 * Example 1: later finished before timeout
 * later resolves after 1 second, timeout function rejects after 3 seconds
 * so we end up in the `.then` block with `val == 42`
 */
Promise.race([later(42, 1), timeout(3)])
    .then(val => {
        // do somethign with val...
        console.log(val)
    }).catch(err => {
        if (err === "TIMEOUT_ERROR") {
            console.log("we timed out!")
        } else {
            consle.log("something failed (but it was not a timeout)")
        }
    });

/*
 * Example 2 (using async/await syntax): we timeout before later returns.
 * later resolves after 3 seconds, timeout function rejects after 2 seconds
 * so we end up in the `.catch` block with `err == "TIMEOUT_ERROR"`
 */
try {
    const val = await Promise.race([later(11, 3), timeout(2)]);
    // do something with val...
} catch (err) {
    if (err === "TIMEOUT_ERROR") {
        console.error("we timed out!")
    } else {
        console.error("something failed (but it was not a timeout)")
    }
}


问:
Purchased App in W10 Store remains in trial expired mode
Some customers are reporting that our App in W10 Store remains in trial expired mode even after purchase. THE  warning dialog is given by store itself, we do not have any STORE API implemented in our legacy app.

How to fix?  Nowadays store limits itself the trial period, there is no code needed to app for that.

答:
How to fix? Nowadays store limits itself the trial period, there is no code needed to app for that.

If your app is a desktop application, you need to configure the StoreContextobject to specify the owner window for modal dialogs, or this object will return inaccurate data or errors.

Have you made this configuration? For more details, you could refer to Using the StoreContext class with the Desktop Bridge.


问:
Setting up etw logs in azure table with mvc
Spent more than 4 hours trying to figure out why etw logs wont show up in my tables. I still am unable to figure out why my logs are not showing up in azure table.

EDIT

The service is hosted as cloud service.

Here is how my diagnostics xml looks like. This is auto generated by selecting options in visual studio

```<code><?xml version="1.0" encoding="utf-8"?>
     <DiagnosticsConfiguration xmlns="http://schemas.microsoft.com/ServiceHosting/2010/10/DiagnosticsConfiguration">
  <PublicConfig xmlns="http://schemas.microsoft.com/ServiceHosting/2010/10/DiagnosticsConfiguration">
    <WadCfg>
      <DiagnosticMonitorConfiguration overallQuotaInMB="4096">
        <EtwProviders>
          <EtwEventSourceProviderConfiguration provider="AzureEventSource">
            <Event id="1" eventDestination="Error" />
            <Event id="2" eventDestination="Warning" />
            <Event id="3" eventDestination="Debug" />
            <Event id="4" eventDestination="Performance" />
            <DefaultEvents eventDestination="Default" />
          </EtwEventSourceProviderConfiguration>
        </EtwProviders>
        <Logs scheduledTransferPeriod="PT2M" />
      </DiagnosticMonitorConfiguration>
    </WadCfg>
    <StorageAccount />
  </PublicConfig>
  <PrivateConfig xmlns="http://schemas.microsoft.com/ServiceHosting/2010/10/DiagnosticsConfiguration">
    <StorageAccount endpoint="" />
  </PrivateConfig>
  <IsEnabled>true</IsEnabled>
</DiagnosticsConfiguration>
</code>```

This is how my class looks like

```<code>using Microsoft.Diagnostics.Tracing;
namespace CommonUtils
    internal sealed class AzureEventSource : EventSource, ILogger
    {
        public AzureEventSource(Type owner) : base(owner.FullName)
        {
        }

        private bool IsInputInvalid(String message)
        {
            return String.IsNullOrWhiteSpace(message);
        }

        public void Error(string message, params object[] args)
        {
            if (IsInputInvalid(message))
            {
                throw new ArgumentNullException("message");
            }

            this.WriteEvent(1, string.Format(message, args));
        }
    }
}
</code>```

I am pretty sure I am missing something simple.

Any help will be greatly appreciated

答:
Assuming you're referring to Microsoft.Diagnostics.Tracing.EventSource in your above example.

You're missing EventSource Event attributes for your class and method respectively.

A simple hello world of eventsource looks like this.

```<code>[EventSource(Name = "HelloEventSource")]
internal sealed class HelloEventSource : EventSource
{
    [Event(1, Level = EventLevel.Informational, Message = "Hello World! {0}")]
    public void HelloWorld(string name)
    {
        WriteEvent(1, name);
    }
}
</code>```

You should fix the tracing part of your code and check the logs are getting generated locally on your machine/vm.
Sending the events via diagnostics pipeline of your choice comes next.

Body:
Spent more than 4 hours trying to figure out why etw logs wont show up in my tables. I still am unable to figure out why my logs are not showing up in azure table.

EDIT

The service is hosted as cloud service.

Here is how my diagnostics xml looks like. This is auto generated by selecting options in visual studio

<?xml version="1.0" encoding="utf-8"?>
     <DiagnosticsConfiguration xmlns="http://schemas.microsoft.com/ServiceHosting/2010/10/DiagnosticsConfiguration">
  <PublicConfig xmlns="http://schemas.microsoft.com/ServiceHosting/2010/10/DiagnosticsConfiguration">
    <WadCfg>
      <DiagnosticMonitorConfiguration overallQuotaInMB="4096">
        <EtwProviders>
          <EtwEventSourceProviderConfiguration provider="AzureEventSource">
            <Event id="1" eventDestination="Error" />
            <Event id="2" eventDestination="Warning" />
            <Event id="3" eventDestination="Debug" />
            <Event id="4" eventDestination="Performance" />
            <DefaultEvents eventDestination="Default" />
          </EtwEventSourceProviderConfiguration>
        </EtwProviders>
        <Logs scheduledTransferPeriod="PT2M" />
      </DiagnosticMonitorConfiguration>
    </WadCfg>
    <StorageAccount />
  </PublicConfig>
  <PrivateConfig xmlns="http://schemas.microsoft.com/ServiceHosting/2010/10/DiagnosticsConfiguration">
    <StorageAccount endpoint="" />
  </PrivateConfig>
  <IsEnabled>true</IsEnabled>
</DiagnosticsConfiguration>

This is how my class looks like

using Microsoft.Diagnostics.Tracing;
namespace CommonUtils
    internal sealed class AzureEventSource : EventSource, ILogger
    {
        public AzureEventSource(Type owner) : base(owner.FullName)
        {
        }

        private bool IsInputInvalid(String message)
        {
            return String.IsNullOrWhiteSpace(message);
        }

        public void Error(string message, params object[] args)
        {
            if (IsInputInvalid(message))
            {
                throw new ArgumentNullException("message");
            }

            this.WriteEvent(1, string.Format(message, args));
        }
    }
}

I am pretty sure I am missing something simple.

Any help will be greatly appreciated

Body:
Assuming you're referring to Microsoft.Diagnostics.Tracing.EventSource in your above example.

You're missing EventSource Event attributes for your class and method respectively.

A simple hello world of eventsource looks like this.

[EventSource(Name = "HelloEventSource")]
internal sealed class HelloEventSource : EventSource
{
    [Event(1, Level = EventLevel.Informational, Message = "Hello World! {0}")]
    public void HelloWorld(string name)
    {
        WriteEvent(1, name);
    }
}

You should fix the tracing part of your code and check the logs are getting generated locally on your machine/vm.
Sending the events via diagnostics pipeline of your choice comes next.


问:
How to evaluate distortion correction algorithm
i am trying to evaluate distortion correction by line fitting algorithm. Now i want to make a decision whether the given image is corrected or not. So should i consider RMSE for overall image, because i get RMSE for each line in image. Please suggest me how to make decision.</p>

答:
Afraid you are doing it all wrong, sorry. The mantra that "a well calibrated camera maps straight lines in the world to straight lines in the image", while true, does not lend itself to a well-posed definition of a metric for the quality of your calibration. You can compute an RMSE on straight lines in various ways, but they are all unprincipled hacks.

You can only define the RMSE error for the entire model of the projection from 3D points to their image. In other words, it only makes sense to speak of RMSE when you are doing bundle adjustment, solving jointly for the pose of the camera, and the linear and nonlinear intrinsic parameters of the lens. This is what you do when you calibrate a camera, or solve a structure-from-motion problem by bundle adjustment.

While it is theoretically true that a perfect estimation of the nonlinear lens distortion parameters "straightens" lines perfectly, it is quite tricky to use just this fact in order to define a metric for the quality of practically estimated distortion parameters. There are several reasons for this, among them:

When you apply a least-squares straight-line fitting algorithm on points obtained by un-distorting with erroneous parameters you are are using a wrong model. Applying the un-distortion function itself to the image of a physical straight 3D line produces a curve in the image which is only straight if the parameters are well estimated. When they aren't, your line fit will be biased, which means that distance between the curve and the straight line it "fits" is not a purely random variable: it depends on where you measure it, and where the curve itself is located in the image.

It is tricky to define a distance between a curve and a straight line that supposedly fits it. How do you choose which point on the line corresponds to a given point on the curve, or viceversa?

A more principled approach would be to define an error measure based on the geometrical curvature of the curve resulting by un-distorting the image of a physical straight line. However, attempting to accurately measure curvature opens a can of worms by itself, since it amounts to estimating (explicitly or not) the first and second derivatives of the curve, which amplifies noise.

So, all in all, either one of your suggestion "works" in the sense that it gives you a number that, if small, is "suggestive" of likely good calibration. However, neither is a "correct" choice, because the basis of what you are trying to measure (and define an error for) is shaky.


问:
Automating a button click issue
I'm having some trouble with automating a button test.
How can I automate a test with Java&Selenium to auto-click this following button?

```<code><button class="btn btn-default primary-bg btn-lg">Submit</button>
</code>```

I tried this:

```<code>driver.findElement(By.xpath("//button[@class= .btn btn-default primary-bg btn-lg']")).click();
</code>```

What am I doing wrong? What other solutions are there?

答:
If this button is this only one on page with this class:

```<code>driver.findElement(By.className("btn-default")).click();
</code>```

If you have more buttons with same class:

```<code>List<WebElement> btnList =driver.findElements(By.className("btn-default")).click();
for(WebElement btn : btnList){
  if(btn.getText().equals("Submit"){
    btn.click();
  }
}
</code>```

Title: Automating a button click issue

Body:
I'm having some trouble with automating a button test.
How can I automate a test with Java&Selenium to auto-click this following button?

<button class="btn btn-default primary-bg btn-lg">Submit</button>

I tried this:

driver.findElement(By.xpath("//button[@class= .btn btn-default primary-bg btn-lg']")).click();

What am I doing wrong? What other solutions are there?

Body:
If this button is this only one on page with this class:

driver.findElement(By.className("btn-default")).click();

If you have more buttons with same class:

List<WebElement> btnList =driver.findElements(By.className("btn-default")).click();
for(WebElement btn : btnList){
  if(btn.getText().equals("Submit"){
    btn.click();
  }
}