Using Android Studio, I created an activity which consists of a form that allows the user to add items to the database in the table which the user wishes. In terms of design, everything works well so far. I am using spinner in order to retrieve a particular column from a table and display the data in the spinner, however, whenever I run the application on Emulator/smartphone it does not display the data which I retrieved from the database (connection to the database was indeed successful and the data was outputted in json format in web browser). Any suggestions on this? Many thanks.
On a different laptop, a new android studio project was created and the code which I've shown here was run for testing purposes. Apparently, the spinner worked when I tried this, I have no idea why but I suspected different Gradle or Android studio versions?
public class add_activity extends AppCompatActivity {
private int PICK_IMAGE_REQUEST = 1;
private static final String typearray = "type_name";
private static final String type = "type_name";
private static final String JSON_ARRAY ="result";
private JSONArray result;
private Button btn_choose ;
Spinner spinner;
private ArrayList<String> arrayList;
TextView food_type;
String type_name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
btn_choose = findViewById(R.id.btn_choosedesign);
this.spinner = (Spinner) findViewById(R.id.spinnertype);
food_type = (TextView) findViewById(R.id.hiddentype);
// findViewById(R.id.hiddentype).setVisibility(View.GONE);
arrayList = new ArrayList<String>();
getdata();
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Setting the values to textviews for a selected item
food_type.setText(getlocation(position));
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
food_type.setText("");
}
});
btn_choose.setOnClickListener(new View.OnClickListener() {
...
}
});
}
private void showFileChooser() {
...
}
private void getdata() {
StringRequest stringRequest = new StringRequest("http://.../.../gettype.php",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
j = new JSONObject(response);
result = j.getJSONArray(JSON_ARRAY);
details(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
private void details(JSONArray j) {
for (int i = 0; i < j.length(); i++) {
try {
JSONObject json = j.getJSONObject(i);
arrayList.add(json.getString(typearray));
} catch (JSONException e) {
e.printStackTrace();
}
}
this.spinner.setAdapter(new ArrayAdapter<>(add_activity.this, android.R.layout.simple_spinner_dropdown_item, arrayList));
}
//Method to get location name which user selects
private String getlocation(int position) { // method is used to post name of marker to database accordingly
String loc = "";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching location from that object
loc = json.getString(type);
} catch (JSONException e) {
e.printStackTrace();
}
//Return location
return loc;
}
}
Related
The app doesn't show anything in the recycler view the first time I open it, but it shows the items after I press the home button and then press the overview button and open the app from there
here is the code in mainActivity
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mlayoutManager;
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<String> countryNmaeList =new ArrayList<>();
final ArrayList<countryItem> countryList = new ArrayList<>();
final ProgressDialog dialog = new ProgressDialog(this);
dialog.setMessage("Loading data");
mRecyclerView = findViewById(R.id.recyclerView);
mAdapter=new countryAdapter(countryList);
mlayoutManager=new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mlayoutManager);
dialog.show();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://covid-193.p.rapidapi.com/statistics")
.get()
.addHeader("x-rapidapi-host", "covid-193.p.rapidapi.com")
.addHeader("x-rapidapi-key", "xxxxxxxxxxxxx")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
dialog.dismiss();
String response1=response.body().string();
try {
//geting Jason object
JSONObject jsonObject=new JSONObject(response1);
JSONArray jsonArray = jsonObject.getJSONArray("response");
for (int i=0;i<jsonArray.length();i++){
JSONObject country = jsonArray.getJSONObject(i);
JSONObject cases = country.getJSONObject("cases");
int activecaseint = cases.getInt("active");
int recoveredint =cases.getInt("recovered");
JSONObject death= country.getJSONObject("deaths");
int dtotal = death.getInt("total");
//adding items into country items
countryList.add(new countryItem(country.getString("country"),String.valueOf(activecaseint),String.valueOf(recoveredint),String.valueOf(dtotal)));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
//nottifying the dataset changed
mAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mAdapter);
}
}
here is my adapter activity
countryAdapter.java
public class countryAdapter extends RecyclerView.Adapter<countryAdapter.countryViewHolder> {
private ArrayList<countryItem> mCountryList;
public static class countryViewHolder extends RecyclerView.ViewHolder{
public TextView mCountryName;
public TextView mActivePatients;
public TextView mRecovered;
public TextView mDeath;
public countryViewHolder(#NonNull View itemView) {
super(itemView);
mCountryName=itemView.findViewById(R.id.CountyNameTv);
mActivePatients=itemView.findViewById(R.id.activePatientsTv);
mRecovered=itemView.findViewById(R.id.recoveredTv);
mDeath=itemView.findViewById(R.id.deathTv);
}
}
public countryAdapter(ArrayList<countryItem> countryList){
mCountryList = countryList;
}
#NonNull
#Override
public countryViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.itemview,parent,false);
countryViewHolder cvh =new countryViewHolder(v);
return cvh;
}
#Override
public void onBindViewHolder(#NonNull countryViewHolder holder, int position) {
countryItem currentItem=mCountryList.get(position);
holder.mCountryName.setText(currentItem.getCountryname());
holder.mActivePatients.setText(currentItem.getActivePatients());
holder.mRecovered.setText(currentItem.getRecovered());
holder.mDeath.setText(currentItem.getDeath());
}
#Override
public int getItemCount() {
return mCountryList.size();
}
public void swapData(ArrayList<countryItem> list) {
if (list != null) {
this.mCountryList.clear();
this.mCountryList.addAll(list);
notifyDataSetChanged();
}
}
}
i have tried putting notifyDataSetChanged inside the try but that didn't work. i hope you can find a way to fix this.
When you have new datalist update after adding it in list as:
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
dialog.dismiss();
String response1=response.body().string();
try {
//geting Jason object
JSONObject jsonObject=new JSONObject(response1);
JSONArray jsonArray = jsonObject.getJSONArray("response");
for (int i=0;i<jsonArray.length();i++){
JSONObject country = jsonArray.getJSONObject(i);
JSONObject cases = country.getJSONObject("cases");
int activecaseint = cases.getInt("active");
int recoveredint =cases.getInt("recovered");
JSONObject death= country.getJSONObject("deaths");
int dtotal = death.getInt("total");
//adding items into country items
countryList.add(new countryItem(country.getString("country"),String.valueOf(activecaseint),String.valueOf(recoveredint),String.valueOf(dtotal)));
}
//adapter.swapData(countryList);
updateData(countryList);
} catch (JSONException e) {
e.printStackTrace();
}
}
you can comment out following line:
mAdapter.notifyDataSetChanged();
Add this function in your adapter class and call it when you need to update list:
public void swapData(ArrayList<countryItem> list) {
if (list != null) {
this.arrayList.clear();
this.arrayList.addAll(list);
notifyDataSetChanged();
}
}
In your global object declaration change type of adapter to:
private countryAdapter mAdapter;
add this method in mainActivity and call when you want to update data:
public void updateData(ArrayList<countryItem> countryList) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
mAdapter.swapData(countryList);
}
});
}
Instead of calling mAdapter.notifyDataSetChanged() at the end of onCreate() you should call it in onRespone() when the new data got set.
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
dialog.dismiss();
String response1=response.body().string();
try {
//geting Jason object
JSONObject jsonObject=new JSONObject(response1);
JSONArray jsonArray = jsonObject.getJSONArray("response");
for (int i=0;i<jsonArray.length();i++){
JSONObject country = jsonArray.getJSONObject(i);
JSONObject cases = country.getJSONObject("cases");
int activecaseint = cases.getInt("active");
int recoveredint =cases.getInt("recovered");
JSONObject death= country.getJSONObject("deaths");
int dtotal = death.getInt("total");
//adding items into country items
countryList.add(new countryItem(country.getString("country"),String.valueOf(activecaseint),String.valueOf(recoveredint),String.valueOf(dtotal)));
}
mAdapter.notifyDataSetChanged(); // ← notify adapter here!
} catch (JSONException e) {
e.printStackTrace();
}
}
UPDATE:
I found the problem, the problem may cause by get the adapter content from SQL requset. Now I post my getLockerList() code here now.
I tested the function with long string
"asdajdnajkdaadasdaajd najkdaadasdaajdnajkdaadasdaajdnajkdaadasdaajdnaj kdaadasdaajdnajkdaadasdasdas"
and it still could work perfectly, so now I guess the problem is come from when I got the data.
I set a spinner with arrayadapter. The content of adapter is come from MySQL request.
I got the data and create the adapter successfully, but when I try to show what item was selected by user, it show nothing after I click the item.
I've tried add some system print to find out the problem, finally I found that the problem is the listener not even call, no matter onItemSelected or onNothingSelected
I think I may find the problem now, my view list is stored different location which is very long String. I tried change the content of the adapter to "test" and it work perfectly. So now the problem is now can I display the long string?
Here is my code:
public class PlaceOrderActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private Spinner from_spinner;
private ArrayList<String> locker_list = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_order);
getLockerList();
from_spinner = (Spinner) findViewById(R.id.from_spinner);
from_spinner.setVisibility(View.VISIBLE);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,locker_list);
from_spinner.setAdapter(adapter);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
from_spinner.setOnItemSelectedListener(this);
}
private void getLockerList() {
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray jsonResponse = new JSONArray(response);
//JSONObject jsonObject = jsonResponse.getJSONObject(0);
if (jsonResponse!=null) {
// System.out.println(jsonResponse);
for (int i=0;i< jsonResponse.length();i++)
{
JSONObject jsonObject = jsonResponse.getJSONObject(i);
String location = jsonObject.getString("location1")+" "+jsonObject.getString("location2")+" "+jsonObject.getString("location3");
locker_list.add(location);
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error);
}
};
getLoockerLocationRequest request = new getLoockerLocationRequest(responseListener,errorListener);
RequestQueue queue = Volley.newRequestQueue(PlaceOrderActivity.this);
queue.add(request);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
System.out.println("selected item");
Toast.makeText(parent.getContext(),from_spinner.getSelectedItem().toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
System.out.println("nothing select");
String no_selected_value = "Select the location";
Toast.makeText(parent.getContext(),no_selected_value,
Toast.LENGTH_SHORT).show();
}
}
I solved the problem.
I don't know what is the concept of it. But if I add one extra item to the arraylist, no matter the item is "" (just blank/nothing inside) or "#######################################"
The program will became could run perfectly.
So I just add one locker_list.add(""); before the adapter create.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_order);
locker_list.add("");
getLockerList();
from_spinner = (Spinner) findViewById(R.id.from_spinner);
from_spinner.setVisibility(View.VISIBLE);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,locker_list);
from_spinner.setAdapter(adapter);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
from_spinner.setOnItemSelectedListener(this);
}
from my question above, I actually want to test the existing codes that I from the Internet. I succesffuly can grab the data from a column in a table and shows back the data. For example, I when i choose person name's "Lim AI Khoon" the it wil display Lim Ai Khoon Names, and also Lim Ai Khoon's badge ID on the same activity. Now, how can I save the data that had being selected to sharedPreferences and display the data at next activity? Below is my code
//MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing the ArrayList
students = new ArrayList<String>();
//Initializing Spinner
spinner = (Spinner) findViewById(R.id.spinner);
//Adding an Item Selected Listener to our Spinner
//As we have implemented the class Spinner.OnItemSelectedListener to this class iteself we are passing this to setOnItemSelectedListener
spinner.setOnItemSelectedListener(this);
//Initializing TextViews
tvName = (TextView) findViewById(R.id.tvName);
tvBadgeID = (TextView) findViewById(R.id.tvBadgeID);
btnNext = findViewById(R.id.btnNext);
//This method will fetch the data from the URL
getData();
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Main2Activity.class);
startActivity(intent);
}
});
}
private void getData(){
//Creating a string request
StringRequest stringRequest = new StringRequest(Config.DATA_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
result = j.getJSONArray(Config.JSON_ARRAY);
//Calling method getStudents to get the students from the JSON Array
getStudents(result);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getStudents(JSONArray j){
//Traversing through all the items in the json array
for(int i=0;i<j.length();i++){
try {
//Getting json object
JSONObject json = j.getJSONObject(i);
//Adding the name of the student to array list
students.add(json.getString(Config.TAG_NAME));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, students));
SharedPreferences sharedPref = getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("reviewer",spinner.getSelectedItem().toString());
}
//Method to get student name of a particular position
private String getName(int position){
String name="";
try {
//Getting object of given index
JSONObject json = result.getJSONObject(position);
//Fetching name from that object
name = json.getString(Config.TAG_NAME);
} catch (JSONException e) {
e.printStackTrace();
}
//Returning the name
return name;
}
//Doing the same with this method as we did with getName()
private String getCourse(int position){
String course="";
try {
JSONObject json = result.getJSONObject(position);
course = json.getString(Config.TAG_BADGEID);
} catch (JSONException e) {
e.printStackTrace();
}
return course;
}
//this method will execute when we pic an item from the spinner
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Setting the values to textviews for a selected item
tvName.setText(getName(position));
tvBadgeID.setText(getCourse(position));
}
//When no item is selected this method would execute
#Override
public void onNothingSelected(AdapterView<?> parent) {
tvName.setText("");
tvBadgeID.setText("");
}
//Config.java
public class Config {
//JSON URL
public static final String DATA_URL = "http://10.0.2.2/spinner/getData.php";
//Tags used in the JSON String
public static final String TAG_NAME = "name";
public static final String TAG_BADGEID = "badgeid";
//JSON array name
public static final String JSON_ARRAY = "result";}
You missed one step,after this
editor.putString("reviewer",spinner.getSelectedItem().toString());
you need save the change ,put this line below :
editor.commit();
with that should work.
I'm new to Android development and Java in general, so I was wondering if someone could point me in the right direction.
I'm writing a currency convertor app and using Volley requests to send a request to an API to retrieve conversion rates.
Right now I am hardcoding the countries into the URL, which works as the conversion rate is successfully retrieved and displayed. I have two Spinners right now and the goal is to retrieve the string value of the selected Spinner value and then use those values for the json request.
I've created two setOnItemSelectedListeners for both Spinners and set the variable containing the value of the string to that. However, I'm getting an null object reference.
Here is what I have:
public class MainActivity extends AppCompatActivity {
RequestQueue rq;
Double conversionDouble;
Spinner toSpinner, fromSpinner;
Spinner toSpinnerText, fromSpinnerText;
private Button convertBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addItemsOnToSpinner();
addListenerOnButton();
jsonSendRequest();
Button convertBtn = (Button) findViewById(R.id.convertBtn);
final EditText fromAmountEditText = findViewById(R.id.fromAmountEditText);
convertBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView toAmountTextView = findViewById(R.id.toAmountTextView);
DecimalFormat percentageFormat = new DecimalFormat("0.00");
Double fromAmount = Double.parseDouble(fromAmountEditText.getText().toString());
String result = "$" + percentageFormat.format(conversionDouble*fromAmount);
toAmountTextView.setText(result);
}
});
rq = Volley.newRequestQueue(this);
}
public void jsonSendRequest() {
RequestQueue queue = Volley.newRequestQueue(this);
// String url = "http://free.currencyconverterapi.com/api/v3/convert?q=CAD_USD&compact=ultra";
String url = "http://free.currencyconverterapi.com/api/v3/convert?q=" + fromSpinnerText + "_" + toSpinnerText + "&compact=ultra";
// Request a string response
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject jsonobject = null;
try {
jsonobject = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
if (jsonobject.has(fromSpinnerText + "_" + toSpinnerText)) {
try {
conversionDouble = jsonobject.getDouble(fromSpinnerText + "_" + toSpinnerText);
// conversionDouble = jsonobject.getDouble(fromSpinnerText + "_" + toSpinnerText);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
public void addItemsOnToSpinner(){
Spinner toSpinner = (Spinner) findViewById(R.id.toSpinner);
Spinner fromSpinner = (Spinner) findViewById(R.id.fromSpinner);
List<String> currency = new ArrayList<String>();
currency.add("USD");
currency.add("CAD");
currency.add("CNY");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, currency
);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
toSpinner.setAdapter(dataAdapter);
fromSpinner.setAdapter(dataAdapter);
fromSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String fromSpinnerText = (String) parent.getItemAtPosition(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
toSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String toSpinnerText = (String) parent.getItemAtPosition(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void addListenerOnButton() {
Spinner fromSpinner = (Spinner) findViewById(R.id.fromSpinner);
Spinner toSpinner = (Spinner) findViewById(R.id.toSpinner);
Button convertBtn = (Button) findViewById(R.id.convertBtn);
}
}
Any help is appreciated.
You have declared a few class variables related to your Spinner:
Spinner toSpinner, fromSpinner;
Spinner toSpinnerText, fromSpinnerText;
You have also correctly defined the onItemSelected() method for the setOnItemSelectedListener.
But, I assume you meant to make the class variables Spinner toSpinnerText, fromSpinnerText; to actually be:
String toSpinnerText = "";
String fromSpinnerText= "";
So that you could call:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
fromSpinnerText = (String) parent.getItemAtPosition(position);
}
Notice that the variable fromSpinnerText in the method is now using the class variable instead of the local variable you defined inside the onItemSelected() method.
The same goes for the onItemSelected() method for the other Spinner and toSpinnerText.
I am using a git repo called LikeButton, but the state of my button keeps jumping around in my recyclerview? Here is the repo https://github.com/jd-alexander/LikeButton. Basically when I click on a recyclerview item, it sets a textview to the word true or false based on if the user liked the post or not, and this works. However, the state of my button is doing some weird stuff, it jumps around...
Here is my Adapter, is their anything wrong with it?
public class ViewpagerAdapter extends RecyclerView.Adapter<ViewpagerAdapter.ViewDashboard>{
private LayoutInflater mLayoutInflater;
private ArrayList<QuestionData> data = new ArrayList<>();
public ViewpagerAdapter(Context context) {
mLayoutInflater=LayoutInflater.from(context);
}
public void setBloglist(ArrayList<QuestionData> listBlogs) {
this.data = listBlogs;
notifyItemRangeChanged(0,listBlogs.size());
}
#Override
public ViewDashboard onCreateViewHolder(ViewGroup parent, int viewType) {
View view = mLayoutInflater.inflate(R.layout.customizejson, parent, false);
ViewDashboard viewholder = new ViewDashboard(view);
return viewholder;
}
#Override
public void onBindViewHolder(ViewDashboard holder, int position) {
QuestionData questionHolder = data.get(position);
holder.questionText.setText(questionHolder.getMtext());
//This sets the text, to a true or a false String
holder.mStudentVoted.setText(questionHolder.getVoters());
holder.mLikeButton.setTag(holder);
}
#Override
public int getItemCount() {
return data.size();
}
class ViewDashboard extends RecyclerView.ViewHolder {
private TextView questionText;
private LikeButton mLikeButton;
private TextView mStudentVoted;
public ViewDashboard(View itemView) {
super(itemView);
questionText = (TextView)itemView.findViewById(R.id.questionText);
mStudentVoted = (TextView)itemView.findViewById(R.id.studentVoted);
mLikeButton = (LikeButton)itemView.findViewById(R.id.like_button_viewpager);
mLikeButton.setOnLikeListener(new OnLikeListener() {
#Override
public void liked(LikeButton likeButton) {
Voting voting = new Voting(getAdapterPosition(),ViewpagerAdapter.this, questionId);
voting.onUpVote();
}
#Override
public void unLiked(LikeButton likeButton) {
Voting voting = new Voting(getAdapterPosition(),ViewpagerAdapter.this, questionId);
voting.onDownVote();
}
});
}
}
}
Voting Class
public class Voting {
private int adapterPosition;
private RecyclerView.Adapter adapter;
private String stringId;
private TextView studentVoted;
//TODO Trim Constructor
public Voting(int adapterPosition,final RecyclerView.Adapter adapter, TextView questionId, TextView studentVoted) {
stringId = questionId.getText().toString();
this.adapter = adapter;
this.studentVoted=studentVoted;
}
public void onUpVote() {
final RequestQueue mRequestQueue = VolleySingleton.getInstance().getRequestQueue();
StringRequest postVoteUp = new StringRequest(Request.Method.PUT, PUT_VOTE_UP, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
System.out.println("Succesful Upvote The Students Value is " + studentVoted);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("failed Upvote");
}
});
mRequestQueue.add(postVoteUp);
}
public void onDownVote() {
final RequestQueue mrequestQueue = VolleySingleton.getInstance().getRequestQueue();
//TODO Delete Token(inserted for student 3 for testing purposes)
StringRequest postVoteDown = new StringRequest(Request.Method.PUT, PUT_VOTE_DOWN, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//TODO OnResponse, must setLiked(False)
//Succesful downVote The Students Value is true
//studentVoted.setText("false");
System.out.println("Succesful downVote The Students Value is "+studentVoted);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println("failed downVote");
}
});
mrequestQueue.add(postVoteDown);
}
public void realTimeUpVoting(TextView textView){
String voteString= textView.getText().toString();
int voteNumber=Integer.parseInt(voteString)+1;
textView.setText("" + voteNumber);
}
public void realTimeDownVoting(TextView textView){
String voteString= textView.getText().toString();
int voteNumber=Integer.parseInt(voteString)-1;
textView.setText("" + voteNumber);
}
}
Json Request and Parsing Methods
public void JsonRequestMethod() {
mVolleySingleton = VolleySingleton.getInstance();
mRequestQueue = mVolleySingleton.getRequestQueue();
JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, URL_HOME, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
mListblogs.clear();
mListblogs = new YourTask().execute(response).get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(request);
}
private ArrayList<QuestionData> parseJSONResponse(JSONArray response) {
if (!response.equals("")) {
try {
StringBuilder data = new StringBuilder();
for (int x = 0; x < response.length(); x++) {
JSONObject currentQuestions = response.getJSONObject(x);
JSONArray arrSubcategory = currentQuestions.optJSONArray("questions");
for (int y = 0; y < arrSubcategory.length(); y++) {
JSONObject objectSubcategory = arrSubcategory.getJSONObject(y);
String text = objectSubcategory.optString("text");
String studentId = objectSubcategory.optString("studentId");
String votes=objectSubcategory.optString("votes");
/*JSONArray cycles through the array of voters, when a user votes
their ID is added to the array.When they downvote, it is removed
*/
JSONArray voters= objectSubcategory.optJSONArray("voters");
QuestionData questionData = new QuestionData();
questionData.setMstudentId(studentId);
questionData.setMtext(text);
questionData.setVotes(votes);
questionData.setVoters(checkIfVoted(voters));
mQuestionDataArrayList.add(questionData);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
return mQuestionDataArrayList;
}
private static String checkIfVoted(JSONArray jsonArray ) {
/*pass in a json Array, copy the array into ints, and if
the students Id is contained in the array return the string true
*/
int[] voteIds = new int[jsonArray.length()];
for(int i=0;i<voteIds.length;i++){
voteIds[i] = jsonArray.optInt(i);
}
for(int i=0;i<voteIds.length;i++){
if(voteIds[i]== Integer.parseInt(Login.getUserId())){
//TODO String was only used for Testing purposes, Convert to Boolean later
return "true";
}
}
return "false";
}
you are currently only updating the textview which is why your recycleview changes state when scrolling.
Should change your voting class and pass the question Data rather textview
public Voting(int adapterPosition,final RecyclerView.Adapter adapter, TextView questionId, TextView studentVoted) {
change to
public Voting(int adapterPosition,final RecyclerView.Adapter adapter, QuestionData questionData, TextView studentVoted) {
// make other changes for the data
and then in
public void realTimeUpVoting(QuestionData questionData){
data.votes++ //something like that. idont know your model
// now call back using interface the recyleview data changed method so it updates the count in recycleview automatically.
Edit
passing the question Data in click button
class ViewDashboard extends RecyclerView.ViewHolder {
public int position
public void onBindViewHolder(ViewDashboard holder, int position) {
holder.position = position
}
public void liked(LikeButton likeButton) {
QuestionData questionHolder = data.get(position);