run select query on multiple conditions - java

i am programming application that should get some information from the DB.
now i am trying to run a select query on multiple where conditions.
i actually try to build the query as a long string by getting array that contain:
user name and mobile.
this is the java code that create the $_POST["invitedUsers"]:
package com.example.matant.gpsportclient.Controllers;
import android.app.Activity;
import android.app.DialogFragment;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import com.example.matant.gpsportclient.AsyncResponse;
import com.example.matant.gpsportclient.MainScreen;
import com.example.matant.gpsportclient.OnCompleteListener;
import com.example.matant.gpsportclient.R;
import com.example.matant.gpsportclient.Utilities.CreateInviteUsersRow;
import com.example.matant.gpsportclient.Utilities.CreateInvitedUsersAdapter;
import com.example.matant.gpsportclient.Utilities.DatePicker;
import com.example.matant.gpsportclient.Utilities.ErrorHandler;
import com.example.matant.gpsportclient.Utilities.MyAdapter;
import com.example.matant.gpsportclient.Utilities.TimePicker;
import com.google.android.gms.maps.model.LatLng;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
public class CreateEventFragmentController extends Fragment implements View.OnClickListener,OnCompleteListener,AsyncResponse {
private Button btnStartdate,btnstartTime,btnendTime,btninviteUsers,btnEndDate,btnSave;
private EditText addressEditText,maxParticipantsEdittext,minAgeEditText;
private CheckBox privateEventCbox,reccuringEventCbox;
private Spinner sportSpinner,genderSpinner;
private Calendar cal;
private String current_time,current_date;
private Boolean SET_TIME = false;
DialogFragment tp = null;
private DBcontroller dbController;
private ProgressDialog progress= null;
private int settime = 0;
private static final int REQUEST_CODE_GET_USER_LIST = 1;
private ListView listViewInvitedUsers;
private List<CreateInviteUsersRow> invitedUsers = null;
private CreateInvitedUsersAdapter invidedAdapter;
public CreateEventFragmentController() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View v = inflater.inflate(R.layout.fragment_create_event_fragment_controller, container, false);
//initialize the widgets
btnStartdate = (Button) v.findViewById(R.id.buttonFromDate);
btnstartTime = (Button) v.findViewById(R.id.buttonFromTime);
btnEndDate = (Button) v.findViewById(R.id.buttonEndDate);
btnendTime = (Button) v.findViewById(R.id.buttonEndTime);
btninviteUsers = (Button) v.findViewById(R.id.buttonInviteUsers);
btnSave = (Button) v.findViewById(R.id.ButtonSave);
cal = Calendar.getInstance();
btnstartTime.setText(getCorrentTime());
btnendTime.setText(getCorrentTime());
btnStartdate.setText(getCurrentDate());
btnEndDate.setText(getCurrentDate());
maxParticipantsEdittext = (EditText) v.findViewById(R.id.editTextMaxPaticipants);
minAgeEditText = (EditText) v.findViewById(R.id.editTextMinAge);
addressEditText = (EditText) v.findViewById(R.id.editTextLocation);
privateEventCbox = (CheckBox) v.findViewById(R.id.checkBoxPrivateEvent);
reccuringEventCbox = (CheckBox) v.findViewById(R.id.checkBoxRecurring);
sportSpinner = (Spinner) v.findViewById(R.id.spinnerSports);
genderSpinner = (Spinner) v.findViewById(R.id.spinnerGender);
//gender spinner
genderSpinner.setAdapter(new MyAdapter(getActivity(), R.layout.custom_spinner, getResources().getStringArray(R.array.eventgender)));
genderSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});//gender spinner
//Sport Spinner
sportSpinner.setAdapter(new MyAdapter(getActivity(), R.layout.custom_spinner, getResources().getStringArray(R.array.kind_of_sport)));
sportSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});//Sport Spinner
btninviteUsers.setVisibility(v.GONE);
//private event check box listener
privateEventCbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (privateEventCbox.isChecked())
btninviteUsers.setVisibility(v.VISIBLE);
else
btninviteUsers.setVisibility(v.GONE);
}
});//private event check box listener
btnstartTime.setOnClickListener(this);
btnendTime.setOnClickListener(this);
btnStartdate.setOnClickListener(this);
btnEndDate.setOnClickListener(this);
btnSave.setOnClickListener(this);
btninviteUsers.setOnClickListener(this);
listViewInvitedUsers = (ListView) v.findViewById(R.id.listViewInvitedusers);
listViewInvitedUsers.setItemsCanFocus(true);
return v;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onClick(View v) {
DialogFragment df = null;
Bundle bundle = null;
String dialog_type ="";
switch(v.getId()) {
case R.id.buttonFromTime:
{
{
bundle = new Bundle();
dialog_type = "Time";
bundle.putInt(dialog_type, 1);
SET_TIME =true;
}
}
break;
case R.id.buttonEndTime:
{
{
bundle = new Bundle();
dialog_type = "Time";
bundle.putInt(dialog_type, 2);
SET_TIME =true;
}
break;
}
case R.id.buttonFromDate:
{
{
bundle = new Bundle();
dialog_type = "Date";
bundle.putInt(dialog_type, 1);
df = new DatePicker();
}
break;
}
case R.id.ButtonSave:
if(validateFields())
sendDataToDBController();
break;
case R.id.buttonInviteUsers: {
Intent i = new Intent(getActivity(),InviteUsersActivity.class);
startActivityForResult(i,REQUEST_CODE_GET_USER_LIST);
break;
}
}
if(df!=null && bundle!=null)
{
df.setArguments(bundle);
df.setTargetFragment(this,0);
df.show(getFragmentManager(),dialog_type);
}
if(SET_TIME)
{
SET_TIME = false;
if(tp == null)
tp = new TimePicker();
tp.setArguments(bundle);
tp.setTargetFragment(this,0);
tp.show(getFragmentManager(),dialog_type);
}
}
#Override
public void onComplete(String flag,String res) {
settime = 0;
switch(flag) {
case "start_time": {
btnstartTime.setText(res);
if (settime == 0)
btnendTime.setText(res);
settime = 0;
break;
}
case "end_time": {
btnendTime.setText(res);
settime = 1;
break;
}
case "date":
btnStartdate.setText(res);
btnEndDate.setText(res);
break;
case "incorrect_time": {
new AlertDialog.Builder(getActivity())
.setTitle("Select Time Error")
.setMessage(res)
.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
btnstartTime.setText(getCorrentTime());
btnendTime.setText(getCorrentTime());
}
})
.setIconAttribute(android.R.attr.alertDialogIcon)
.show();
}
}
}
/**
* return the current time as string
* #return -current time
*/
public String getCorrentTime()
{
String min = "";
if(cal.get(Calendar.MINUTE)<10)
min = "0"+String.valueOf(cal.get(Calendar.MINUTE));
else
min = String.valueOf(cal.get(Calendar.MINUTE));
current_time = cal.get(Calendar.HOUR_OF_DAY)+":"+min;
return current_time;
}
/**
* return the current date
* #return current date
*/
public String getCurrentDate()
{
current_date = cal.get(Calendar.DAY_OF_MONTH)+"/"+(cal.get(Calendar.MONTH)+1)+"/"+cal.get(Calendar.YEAR);
return current_date;
}
/**
* this function convert real address to geographical coordinates.
* #param strAddress -real address
* #return LatLng object which contain the coordinates
*/
public LatLng getLocationFromAddress(String strAddress) {
Geocoder coder = new Geocoder(getActivity());
List<Address> address;
LatLng p1 = null;
try {
address = coder.getFromLocationName(strAddress, 5);
if (address == null) {
return null;
}
Address location = address.get(0);
location.getLatitude();
location.getLongitude();
p1 = new LatLng(location.getLatitude(), location.getLongitude() );
Log.d("coordinates",p1.latitude+""+p1.longitude);
} catch (Exception ex) {
Log.d("Location Exception","error converting address");
ex.printStackTrace();
}
return p1;
}
#Override
public void handleResponse(String resStr) {
progress.dismiss();
Log.d("handleResponse", resStr);
if (resStr != null) {
try {
JSONObject jsonObj = new JSONObject(resStr);
String flg = jsonObj.getString("flag");
switch (flg)
{
case "success": {
Log.d("event created", "success to create event");
new AlertDialog.Builder(getActivity())
.setTitle("Event")
.setMessage("Event was created successfully")
.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getActivity(), MainScreen.class);
startActivity(i);
getActivity().finish();
}
})
.setIconAttribute(android.R.attr.alertDialogIcon)
.show();
break;
}
case "failed":
Log.d("Created failed","failed to create event");
{
new AlertDialog.Builder(getActivity())
.setTitle("Create event failed!")
.setMessage(jsonObj.getString("msg"))
.setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
btnstartTime.setText(getCorrentTime());
btnendTime.setText(getCorrentTime());
}
})
.setIconAttribute(android.R.attr.alertDialogIcon)
.show();
break;
}
case "select failed":
Log.d("select query","failed to find events");
}
}catch (JSONException e){
Log.d("json exception",e.getMessage());
}
}
}
/**
* send request to server
*/
#Override
public void sendDataToDBController() {
LatLng lonlat = getLocationFromAddress(addressEditText.getText().toString());
if(lonlat == null)
{
Log.d("location is:","location not found");
addressEditText.setError("Location was not found!");
return;
}
Log.d("found location",lonlat.latitude+""+lonlat.longitude);
BasicNameValuePair tagreq = new BasicNameValuePair("tag","create_event");
BasicNameValuePair sport = new BasicNameValuePair("sport_type",sportSpinner.getSelectedItem().toString());
Log.d("sport_type",sportSpinner.getSelectedItem().toString());
BasicNameValuePair date = new BasicNameValuePair("date",btnStartdate.getText().toString());
BasicNameValuePair startTime = new BasicNameValuePair("s_time",btnstartTime.getText().toString());
BasicNameValuePair endTime = new BasicNameValuePair("e_time",btnendTime.getText().toString());
BasicNameValuePair longtitude = new BasicNameValuePair("lon",String.valueOf(lonlat.longitude));
BasicNameValuePair latitude = new BasicNameValuePair("lat",String.valueOf(lonlat.latitude));
BasicNameValuePair event_type = new BasicNameValuePair("event_type",String.valueOf(privateEventCbox.isChecked()));
BasicNameValuePair gender = new BasicNameValuePair("gender",String.valueOf(genderSpinner.getSelectedItem().toString()));
BasicNameValuePair min_age = new BasicNameValuePair("minAge",String.valueOf(minAgeEditText.getText()));
BasicNameValuePair participants = new BasicNameValuePair("max_participants",maxParticipantsEdittext.getText().toString());
BasicNameValuePair scheduled = new BasicNameValuePair("scheduled",String.valueOf(reccuringEventCbox.isChecked()));
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
if(invitedUsers != null)
{
if(invitedUsers.size() > 0)
{
JSONArray jsnArr = new JSONArray();
for(int i=0 ; i < invitedUsers.size(); i++)
{
JSONObject jsnObj = new JSONObject();
try {
jsnObj.put(invitedUsers.get(i).getName(), invitedUsers.get(i).getMobile());
jsnArr.put(jsnObj);
} catch (JSONException e) {
e.printStackTrace();
}
}
BasicNameValuePair invitedusers = new BasicNameValuePair("invitedUsers",jsnArr.toString());
nameValuePairList.add(invitedusers);
}
}
nameValuePairList.add(tagreq);
nameValuePairList.add(sport);
nameValuePairList.add(date);
nameValuePairList.add(startTime);
nameValuePairList.add(endTime);
nameValuePairList.add(min_age);
nameValuePairList.add(longtitude);
nameValuePairList.add(latitude);
nameValuePairList.add(event_type);
nameValuePairList.add(participants);
nameValuePairList.add(scheduled);
nameValuePairList.add(gender);
dbController = new DBcontroller(getActivity().getApplicationContext(),this);
dbController.execute(nameValuePairList);
}
#Override
public void preProcess() {
this.progress = ProgressDialog.show(getActivity(), "Create Event",
"Building Event...", true);
}
/**
* check the input of the user.
* #return
*/
public boolean validateFields()
{
Boolean valid = true;
if(addressEditText.getText().toString().equals(""))
{
addressEditText.setError("Location field cannot be empty!");
Log.d("max edittext", "max edit text is empty");
valid = false;
}
if(maxParticipantsEdittext.getText().toString().equals(""))
{
maxParticipantsEdittext.setError("Please insert the max Participants in the event");
valid = false;
} if(minAgeEditText.getText().toString().equals("") == true || Integer.valueOf(minAgeEditText.getText().toString()) < 14)
{
minAgeEditText.setError("Minimal age should be at least 14!");
Log.d("min edittext", "min edit text is empty");
valid = false;
} if(btnendTime.getText().toString().equals(btnstartTime.getText().toString()))
{
onComplete("incorrect_time", "Please Provide end time of the event ");
Log.d("equal time", "time is equal");
valid = false;
}
return valid;
}
/**
* connect with the InviteUserActivity and getting the result from her.
* #param requestCode
* #param resultCode
* #param data
*/
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("inside OnActivityResult","result");
if(REQUEST_CODE_GET_USER_LIST == requestCode){
if(Activity.RESULT_OK == resultCode){
JSONArray res = null;
try {
res = new JSONArray(data.getStringExtra("userList"));
invitedUsers = new ArrayList<CreateInviteUsersRow>();
for(int i=0 ;i< res.length(); i++){
String name = res.getJSONObject(i).getString("name");
String mobile = res.getJSONObject(i).getString("mobile");
CreateInviteUsersRow invitedUserRow = new CreateInviteUsersRow(name,mobile,R.drawable.remove_user_50);
invitedUsers.add(invitedUserRow);
}
invidedAdapter = new CreateInvitedUsersAdapter(getActivity(),R.layout.create_users_invited_item,invitedUsers);
listViewInvitedUsers.setAdapter(invidedAdapter);
invidedAdapter.setAdapterListview(listViewInvitedUsers);
invidedAdapter.setListViewHeightBasedOnChildren();
listViewInvitedUsers = invidedAdapter.getAdapterListview();
} catch (JSONException e) {
e.printStackTrace();
}
Log.d("Users are:",res.toString());
}
if(resultCode == Activity.RESULT_CANCELED){
Log.d("Acttivity canceled","canceled");
}
}
}
}
this is the php code:
<?php
/**
* Created by PhpStorm.
* User: matant
* Date: 9/17/2015
* Time: 2:56 PM
*/
include 'response_process.php';
class CreateEvent implements ResponseProcess {
public function dataProcess($dblink)
{
$output = array();
//$date = $_POST["date"];
$sport = $_POST["sport_type"];
$date = date("Y-m-d",strtotime(str_replace('/','-',$_POST["date"])));
$s_time =$_POST["s_time"];
$e_time = $_POST["e_time"];
$lon = $_POST["lon"];
$lat = $_POST["lat"];
$event_type = $_POST["event_type"];
$max_p = $_POST["max_participants"];
$sched = $_POST["scheduled"];
$gen = $_POST["gender"];
$min_age = $_POST["minAge"];
$query = "SELECT * FROM event WHERE (event.longtitude = '$lon' AND event.latitude = '$lat')
AND event.event_date = '$date' And ((event.start_time BETWEEN '$s_time' AND '$e_time') OR (event.end_time BETWEEN '$s_time' AND '$e_time'))";
//AND (event.start_time = '$s_time' AND event.end_time = '$e_time')
//check time and place of the event
$result_q = mysqli_query($dblink,$query) or die (mysqli_error($dblink));
if(!$result_q)
{
$output["flag"]= "select failed";
$output["msg"] = $result_q;
return json_encode($output);
}
//case date and time are available
else {
$no_of_rows = mysqli_num_rows($result_q);
if ($no_of_rows < 1) {
$output["flag"] = "success";
$output["msg"] = "insert event";
$result = mysqli_query($dblink, "INSERT into event(kind_of_sport,event_date,start_time,end_time,longtitude,latitude,private,gender,min_age,max_participants,scheduled,event_status)
VALUES ('$sport','$date','$s_time','$e_time','$lon','$lat','$event_type','$gen','$min_age','$max_p','$sched','1')") or die (mysqli_error($dblink));
if (!$result) {
$output["flag"] = "failed to create event";
// return (json_encode($output));
}
if(isset($_POST["invitedUsers"])){
$query_id = "SELECT id From event WHERE event.event_date = '$date' and event.start_time = '$s_time' and event.end_time = '$e_time'";
$event_s_res = mysqli_query($dblink,$query_id) or die (mysqli_error($dblink));
if(!$event_s_res)
{
$output["flag"] = "failed";
$output["msg"] = "Event id not found";
}
else{
$row = mysqli_fetch_assoc($event_s_res);
$output["event id"]=$row["id"];
$invited_users = $_POST["invitedUsers"];
$output["users"]=array();
$output["invitedusers"] = $invited_users;
$query_users = "SELECT id From users WHERE ";
$i=0;
foreach($invited_users["users"] as $user) {
if ($i < (count($invited_users) - 1))
// add a space at end of this string
$query_users .= "users.mobile = '" . $user['mobile'] . "' or ";
else {
// and this one too
$query_users .= "users.mobile = '" . $invited_users[$i]['mobile']. "' ";
$output["users"][] = $user['id'];
}
}
$output["user_query"]= $query_users;
$event_user_s_res = mysqli_query($dblink,$query_users) or die (mysqli_error($dblink));
if(!$event_user_s_res)
{
$output["flag"] = "failed";
$output["msg"] = "user id not found";
}
}
}
}
else {
$output["flag"] = "failed";
$output["msg"] = "Place is already occupied in this time";
}
}
return json_encode($output);
}
}
this is the error that i got:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

Try replacing this line
$query_users .= "users.mobile = '".$invited_users[$i]['mobile']."'or";
with this :
$query_users .= "users.mobile = '".$invited_users[$i]['mobile']."' or ";

Besides Codrutz Codrutz answer, will probably need to update
$query_users = "SELECT id From users WHERE";
to
$query_users = "SELECT id From users WHERE ";
as well.

Related

I need to perform add to cart functionality with the option of increment or decrement quantity of item

product quantity changes button but when I click the add to cart button and change the visibility to gone others + , - buttons visibility to visible show on the screen then I click any of this two-button and their listener didn't work and after restarting the app both + , - buttons start working correctly. One more thing, I need my notification badge value shouldn't be changed if one product is already in the cart then changing its quantity, but in my case value change if I increase the quantity or decrease the quantity of the product. Thanks in advance
HomeFragment
package colon.semi.com.dealMall.fragments;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.smarteist.autoimageslider.SliderAnimations;
import com.smarteist.autoimageslider.SliderView;
import java.util.ArrayList;
import java.util.List;
import colon.semi.com.dealMall.R;
import colon.semi.com.dealMall.Utils.AppClass;
import colon.semi.com.dealMall.Utils.Constants;
import colon.semi.com.dealMall.adapters.DealsSliderAdapter;
import colon.semi.com.dealMall.adapters.DevicesParentRecyclerAdapter;
import colon.semi.com.dealMall.adapters.SliderAdapterExample;
import colon.semi.com.dealMall.adapters.TopSellingAdapter;
import colon.semi.com.dealMall.dataModels.CartDataTable;
import colon.semi.com.dealMall.dataModels.CartResponse;
import colon.semi.com.dealMall.dataModels.HomeDataModel;
import colon.semi.com.dealMall.dataModels.ImagesListDM;
import colon.semi.com.dealMall.dataModels.Points;
import colon.semi.com.dealMall.dataModels.Product;
import colon.semi.com.dealMall.dataModels.SliderImagesResponse;
import colon.semi.com.dealMall.dataModels.TopSellingResponse;
import colon.semi.com.dealMall.viewModels.CartViewModel;
import colon.semi.com.dealMall.viewModels.HomeFragmentViewModel;
import colon.semi.com.dealMall.viewModels.PointsViewModel;
public class HomeFragment extends Fragment {
HomeFragmentViewModel homeFragmentViewModel;
View view;
SliderView sliderView;
SliderView imageSliderDeals;
RecyclerView recyclerView;
private ArrayList<String> listTitleRecycler = new ArrayList<>();
DevicesParentRecyclerAdapter homeParentRecyclerAdapter;
boolean topSellingComplete = false;
boolean latestComplete = false;
boolean allproductsComplete = false;
HomeDataModel homeDataModel = new HomeDataModel();
CartViewModel cartViewModel;
ProgressDialog progressDialog;
RecyclerView recylerTimeDeal;
TopSellingAdapter timeDealAdapter;
int[] imgResLounge = {R.drawable.ic_get_free, R.drawable.ic_seasonal_deals,
R.drawable.ic_grocery_deals,
R.drawable.ic_stationary_deals};
//CategoryNames
String[] imgNamesLounge = {"Men\nLounge", "Women\nLounge", "Cosmetic\nLounge", "Garments\nLounge"};
//Liststudent ERP OBJECT
ArrayList<ImagesListDM> loungeList = new ArrayList<>();
SharedPreferences sharedPreferences;
private TextView totalPointsTextView;
private TextView totalPrice;
private PointsViewModel pointsViewModel;
private View viewParent;
private boolean isLogin;
private int userId;
private List<CartDataTable> cartDataTableList = new ArrayList<>();
private int pos;
private int pQun;
private int pId;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_home, container, false);
initViews();
initListeners();
getSliderImages();
// getCartItem();
isLogin = sharedPreferences.getBoolean(Constants.USER_IS_LOGIN, false);
if (Constants.topSellingProduct != null) {
if (!Constants.topSellingProduct.isEmpty()) {
recylerTimeDeal.setLayoutManager(new LinearLayoutManager(getActivity(),
LinearLayoutManager.HORIZONTAL, false));
timeDealAdapter = new TopSellingAdapter(Constants.topSellingProduct, cartDataTableList,
getActivity());
recylerTimeDeal.setAdapter(timeDealAdapter);
clickListner(view);
}
} else {
getTopSellingProducts(1);
}
if (Constants.latestProduct != null) {
if (!Constants.latestProduct.isEmpty()) {
homeDataModel.setLatestList(Constants.latestProduct);
homeParentRecyclerAdapter = new DevicesParentRecyclerAdapter(getActivity(),
homeDataModel);
recyclerView.setAdapter(homeParentRecyclerAdapter);
}
} else {
getLatestProducts(1);
}
if (Constants.allProducts != null) {
if (!Constants.allProducts.isEmpty()) {
homeDataModel.setAllProductList(Constants.allProducts);
homeParentRecyclerAdapter = new DevicesParentRecyclerAdapter(getActivity(),
homeDataModel);
recyclerView.setAdapter(homeParentRecyclerAdapter);
}
} else {
getAllProducts(1);
}
return view;
}
#Override
public void onResume() {
isLogin = sharedPreferences.getBoolean(Constants.USER_IS_LOGIN, false);
// if (isLogin) {
userId = sharedPreferences.getInt(Constants.USER_ID, 0);
cartViewModel.getCartDataTableLiveData(userId).observe(getActivity(), new
Observer<List<CartDataTable>>() {
#Override
public void onChanged(List<CartDataTable> cartDataTables) {
if (cartDataTables != null) {
cartDataTableList = cartDataTables;
}
});
//}
super.onResume();
}
private void clickListner(View view1) {
timeDealAdapter.setOnItemClickListener(new TopSellingAdapter.OnItemClickListener() {
#Override
public void onAddtoCartClick(View view, Product product) {
Log.e("onAddtoCartClick", "called");
userId = sharedPreferences.getInt(Constants.USER_ID, 0);
progressDialog = new ProgressDialog(getActivity());
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Please Wait...");
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
viewParent = (View) view.getParent();
progressDialog.dismiss();
int quantity = 1;
cartViewModel.addProductToCart(userId, product.getProduct_id(),
quantity).observe(getActivity(), new Observer<CartResponse>() {
#Override
public void onChanged(CartResponse cartResponse) {
if (cartResponse != null) {
progressDialog.dismiss();
if (cartResponse.getMessage().equals("Product added successfully")) {
progressDialog.dismiss();
CartDataTable cartDataTable = new CartDataTable();
cartDataTable.setProductId(product.getProduct_id());
cartDataTable.setProductQuantity(1);
cartDataTable.setUserId(userId);
cartViewModel.insertCart(cartDataTable);
progressDialog.invalidateOptionsMenu();
} else {
Toast.makeText(getActivity(), cartResponse.getMessage(),
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getActivity(), "Something went wrong",
Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public void updateCartData(int productId, int quantity, int position, View view) {
pId = productId;
pQun = quantity;
pos = position;
viewParent = (View) view.getParent();
Log.d("updateCartData2", pId + " " + pQun);
CartDataTable cartDataTable = cartViewModel.getCart2(productId, userId);
userId = sharedPreferences.getInt(Constants.USER_ID, 0);
Log.d("userId2", String.valueOf(userId));
if (cartDataTable != null) {
if (pQun == 0) {
cartViewModel.deleteCart(cartDataTable);
} else {
CartDataTable cartDataTable1 = new CartDataTable();
cartDataTable1.setProductQuantity(pQun);
cartDataTable1.setProductId(pId);
cartDataTable1.setCartId(cartDataTable.getCartId());
cartDataTable1.setUserId(userId);
cartViewModel.updateCart(cartDataTable1);
Log.d("cart2", "updated");
}
}
}
});
}
private void getSliderImages() {
if (AppClass.isOnline(getActivity())) {
homeFragmentViewModel.getSliderImages().observe(getActivity(), new
Observer<SliderImagesResponse>() {
#Override
public void onChanged(SliderImagesResponse sliderImagesResponse) {
if (sliderImagesResponse.getStatus() == 1) {
SliderAdapterExample adapter = new SliderAdapterExample(getContext(),
sliderImagesResponse.getData());
sliderView.setSliderAdapter(adapter);
sliderView.setSliderTransformAnimation(SliderAnimations.SIMPLETRANSFORMATION);
sliderView.setAutoCycleDirection(SliderView.AUTO_CYCLE_DIRECTION_BACK_AND_FORTH);
sliderView.setIndicatorSelectedColor(Color.WHITE);
sliderView.setIndicatorUnselectedColor(Color.GRAY);
sliderView.setScrollTimeInSec(4); //set scroll delay in seconds :
sliderView.startAutoCycle();
} else {
progressDialog.dismiss();
Toast.makeText(getContext(), ""+sliderImagesResponse.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
} else {
AppClass.offline(getActivity());
}
}
private void getTopSellingProducts(int page) {
if (AppClass.isOnline(getActivity())) {
progressDialog.show();
homeFragmentViewModel.getTopSellingProducts(page).observe(getActivity(), new
Observer<TopSellingResponse>() {
#Override
public void onChanged(TopSellingResponse topSellingResponse) {
if (topSellingResponse.getStatus() == 1) {
progressDialog.dismiss();
topSellingComplete = true;
Constants.topSellingProduct = topSellingResponse.getData();
recylerTimeDeal.setLayoutManager(new LinearLayoutManager(getActivity(),
LinearLayoutManager.HORIZONTAL, false));
timeDealAdapter = new TopSellingAdapter(topSellingResponse.getData(),
cartDataTableList, getActivity());
recylerTimeDeal.setAdapter(timeDealAdapter);
clickListner(view);
if (latestComplete || allproductsComplete) {
homeParentRecyclerAdapter.notifyDataSetChanged();
} else {
homeParentRecyclerAdapter = new DevicesParentRecyclerAdapter(getActivity(),
homeDataModel);
recyclerView.setAdapter(homeParentRecyclerAdapter);
}
} else {
progressDialog.dismiss();
Toast.makeText(getContext(), ""+topSellingResponse.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
} else {
AppClass.offline(getActivity());
}
}
private void getLatestProducts(int page) {
if (AppClass.isOnline(getActivity())) {
progressDialog.show();
homeFragmentViewModel.getLatestProducts(page).observe(getActivity(), new
Observer<TopSellingResponse>() {
#Override
public void onChanged(TopSellingResponse topSellingResponse) {
if (topSellingResponse.getStatus() == 1) {
progressDialog.dismiss();
latestComplete = true;
Constants.latestProduct = topSellingResponse.getData();
homeDataModel.setLatestList(topSellingResponse.getData());
if(topSellingComplete || allproductsComplete) {
homeParentRecyclerAdapter.notifyDataSetChanged();
} else {
homeParentRecyclerAdapter = new DevicesParentRecyclerAdapter(getActivity(),
homeDataModel);
recyclerView.setAdapter(homeParentRecyclerAdapter);
}
} else {
progressDialog.dismiss();
Toast.makeText(getContext(), ""+topSellingResponse.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
} else {
AppClass.offline(getActivity());
}
}
private void getAllProducts(int page) {
if (AppClass.isOnline(getActivity())) {
progressDialog.show();
homeFragmentViewModel.getAllProducts(page).observe(getActivity(), new
Observer<TopSellingResponse>() {
#Override
public void onChanged(TopSellingResponse topSellingResponse) {
if (topSellingResponse.getStatus() == 1) {
progressDialog.dismiss();
allproductsComplete = true;
Constants.allProducts = topSellingResponse.getData();
homeDataModel.setAllProductList(topSellingResponse.getData());
if(topSellingComplete || latestComplete) {
homeParentRecyclerAdapter.notifyDataSetChanged();
} else {
homeParentRecyclerAdapter = new DevicesParentRecyclerAdapter(getActivity(),
homeDataModel);
recyclerView.setAdapter(homeParentRecyclerAdapter);
}
} else {
progressDialog.dismiss();
Toast.makeText(getContext(), ""+topSellingResponse.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
} else {
AppClass.offline(getActivity());
}
}
private void getPoints(int userId) {
pointsViewModel.getUserPointsById(userId).observe(getActivity(), new Observer<Points>() {
#Override
public void onChanged(Points points) {
progressDialog.dismiss();
if (points.getStatus() == 1) {
progressDialog.dismiss();
if (points.getTotalPoints() != null && points.getTotalDiscount() != null) {
totalPointsTextView.setText(points.getTotalPoints() + "");
totalPrice.setText(points.getTotalDiscount() + "");
} else {
Toast.makeText(getActivity(), "No Data Found", Toast.LENGTH_SHORT).show();
}
} else {
progressDialog.dismiss();
Toast.makeText(getActivity(), points.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
private void initViews() {
homeFragmentViewModel = new ViewModelProvider(this).get(HomeFragmentViewModel.class);
cartViewModel = new ViewModelProvider(this).get(CartViewModel.class);
sliderView = view.findViewById(R.id.imageSlider);
imageSliderDeals = view.findViewById(R.id.imageSliderDeals);
recyclerView = view.findViewById(R.id.recyclerView);
recylerTimeDeal = view.findViewById(R.id.recy_timeDeal);
totalPointsTextView = view.findViewById(R.id.pointsTextView);
totalPrice = view.findViewById(R.id.totalPrice);
pointsViewModel = new ViewModelProvider(this).get(PointsViewModel.class);
sharedPreferences = getActivity().getSharedPreferences(Constants.LOGIN_PREFERENCE,
Context.MODE_PRIVATE);
int userId = sharedPreferences.getInt(Constants.USER_ID, 0);
listTitleRecycler.add(0, "Top Selling");
listTitleRecycler.add(1, "Latest Products");
listTitleRecycler.add(2, "All Products");
homeDataModel.setTitleList(listTitleRecycler);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),
LinearLayoutManager.VERTICAL, false));
recyclerView.setHasFixedSize(true);
progressDialog = new ProgressDialog(getContext(), R.style.exitDialogTheme);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Please wait...");
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
getPoints(userId);
}
private void initListeners() {
addLoungeToList();
DealsSliderAdapter adapter = new DealsSliderAdapter(getContext(), loungeList);
imageSliderDeals.setSliderAdapter(adapter);
imageSliderDeals.setSliderTransformAnimation(SliderAnimations.SIMPLETRANSFORMATION);
imageSliderDeals.setAutoCycleDirection(SliderView.AUTO_CYCLE_DIRECTION_BACK_AND_FORTH);
imageSliderDeals.setScrollTimeInSec(4); //set scroll delay in seconds :
imageSliderDeals.startAutoCycle();
}
public void addLoungeToList() {
int i = 0;
for (String name : imgNamesLounge) {
ImagesListDM imagesListDM = new ImagesListDM();
imagesListDM.setImg(imgResLounge[i]);
imagesListDM.setNameImg(name);
loungeList.add(imagesListDM);
i++;
}
}
}
TopSellingAdapter
package colon.semi.com.dealMall.adapters;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import java.util.ArrayList;
import java.util.List;
import colon.semi.com.dealMall.R;
import colon.semi.com.dealMall.Utils.Constants;
import colon.semi.com.dealMall.dataModels.CartDataTable;
import colon.semi.com.dealMall.dataModels.Product;
import colon.semi.com.dealMall.uiActivities.ProductDetailActivity;
public class
TopSellingAdapter extends RecyclerView.Adapter<TopSellingAdapter.SingleItemRowHolder> {
private static OnItemClickListener mlistener; //just a variable
private ArrayList<Product> topSellingList;
private Context context;
private List<CartDataTable> cartDataTables;
int[] quantity;int[] pid;
int size;
public TopSellingAdapter(ArrayList<Product> topSellingList, List<CartDataTable> cartDataTableList, Context context) {
this.topSellingList = topSellingList;
this.cartDataTables = cartDataTableList;
this.context = context;
}
#Override
public void onBindViewHolder(#NonNull SingleItemRowHolder holder, final int position) {
SingleItemRowHolder viewHolder = (SingleItemRowHolder) holder;
Product product = topSellingList.get(position);
RequestOptions options = new RequestOptions()
.centerInside()
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.skipMemoryCache(true)
.priority(Priority.HIGH);
Glide
.with(context)
.load(topSellingList.get(position).getImage_name())
.apply(options)
.into(viewHolder.image);
viewHolder.name.setText(topSellingList.get(position).getProduct_title());
viewHolder.price.setText(topSellingList.get(position).getPrice());
viewHolder.linear_label.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, ProductDetailActivity.class);
intent.putExtra(Constants.PRODUCT_OBJECT, product);
context.startActivity(intent);
}
});
holder.addtocart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mlistener!=null && position != RecyclerView.NO_POSITION){
viewHolder.addtocart.setVisibility(View.GONE);
viewHolder.cartLayout.setVisibility(View.VISIBLE);
viewHolder.quanTv.setText("1");
mlistener.onAddtoCartClick(v, topSellingList.get(position));
}
}
});
if (cartDataTables != null && cartDataTables.size() > 0) {
for (int i = 0; i < cartDataTables.size(); i++) {
if (cartDataTables.get(i).getProductId() == product.getProduct_id()) {
viewHolder.addtocart.setVisibility(View.GONE);
viewHolder.cartLayout.setVisibility(View.VISIBLE);
viewHolder.quanTv.setText(String.valueOf(cartDataTables.get(i).getProductQuantity()));
}
}
size = cartDataTables.size();
quantity = new int[size];
pid = new int[size];
}
// if (cartDataTables != null && cartDataTables.size() > 0) {
// int size = cartDataTables.size();
// int[] quantity = new int[size];
// int[] pid = new int[size];
Log.d("CartDataSize", String.valueOf(size));
for (int i = 0; i < size; i++) {
quantity[i] = cartDataTables.get(i).getProductQuantity();
pid[i] = cartDataTables.get(i).getProductId();
Log.d("CartData1", quantity[i] + " " + pid[i]);
}
holder.addProdButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < size; i++) {
quantity[i]++;
viewHolder.quanTv.setText(String.valueOf(quantity[i]));
}
// int id = pid[size - 1];
//int q1 = quantity[size - 1];
// Log.d("q1", String.valueOf(q1));
for (int i = 0; i < size; i++) {
if (cartDataTables.get(i).getProductId() == product.getProduct_id()) {
// q1 = q1 + 1;
//Log.d("q2", String.valueOf(q1));
//Toast.makeText(context, String.valueOf(q1), Toast.LENGTH_SHORT).show();
mlistener.updateCartData(pid[i], quantity[i], holder.getAdapterPosition(), v);
}
else {
mlistener.updateCartData(pid[i], quantity[i], holder.getAdapterPosition(), v);
}
}
}
});
holder.minusProdButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < size; i++) {
if (quantity[i] < 1) {
holder.cartLayout.setVisibility(View.GONE);
holder.addtocart.setVisibility(View.VISIBLE);
} else {
quantity[i]--;
if (quantity[i] < 1) {
holder.cartLayout.setVisibility(View.GONE);
holder.addtocart.setVisibility(View.VISIBLE);
}
viewHolder.quanTv.setText(String.valueOf(quantity[i]));
}
}
Toast.makeText(context, "Already added", Toast.LENGTH_SHORT).show();
for (int i = 0; i < size; i++) {
if (cartDataTables.get(i).getProductId() == product.getProduct_id()) {
mlistener.updateCartData(pid[i], quantity[i], holder.getAdapterPosition(),
v);
}
else {
mlistener.updateCartData(pid[i], quantity[i], holder.getAdapterPosition(), v);
}
}
}
});
}
#NonNull
#Override
public SingleItemRowHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.temp_top_selling_products, viewGroup, false);
SingleItemRowHolder categoriesListVH = new SingleItemRowHolder(view);
return categoriesListVH;
}
#Override
public int getItemCount() {
return (null != topSellingList ? topSellingList.size() : 0);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.mlistener = listener;
}
public interface OnItemClickListener {
void onAddtoCartClick(View view, Product product);
void updateCartData(int productId, int quantity, int position, View view);
}
public class SingleItemRowHolder extends RecyclerView.ViewHolder {
ImageView image;
TextView name;
TextView price;
LinearLayout linear_label;
Button addtocart;
Button addProdButton;
Button minusProdButton;
TextView quanTv;
RelativeLayout cartLayout;
public SingleItemRowHolder(View view) {
super(view);
image = view.findViewById(R.id.image);
name = view.findViewById(R.id.name);
price = view.findViewById(R.id.price);
linear_label = view.findViewById(R.id.linear_label);
addtocart = view.findViewById(R.id.addToCartButtonHome);
cartLayout = view.findViewById(R.id.rel_prodCart_home);
addProdButton = view.findViewById(R.id.prodAddButtonHome);
quanTv = view.findViewById(R.id.productQuanTextViewHome);
minusProdButton = view.findViewById(R.id.prodMinusButtonHome);
}
}
}
first time when adapter constructor called there is no data in the cartDataTables list and because of my condition if (cartDataTables != null && cartDataTables.size() > 0), when I click add to cart button they found no data in the cartDataTables list because I didn't call notifyDataSetChanged() method or call the adapter constructor again, and my addtocart click listener is inside this condition if (cartDataTables != null && cartDataTables.size() > 0) that's why add to cart button click listner didn't work.
solution: call the adapter constructor again.

Android Quiz App,back and next buttons issue

I am developing a quiz application,and im facing with a issue with back and next button. Here is the situation:
I have 40 questions in total,and in the java class of quiz i initialize an integer rowID=1
W
hen I'm at the first position the button is disabled, but when I press next still it stays disabled, the same thing for next button
I have a TextView which shows the number of current question, and if I'm at the question number 40 and I press next again, it goes 41. it shouldn't go
Here is my code:
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Html;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.shawnlin.numberpicker.NumberPicker;
import org.json.JSONObject;
import java.util.List;
import java.util.concurrent.TimeUnit;
import retrofit2.Call;
import retrofit2.Callback;
import static autoshkolla.almotech.org.autoshkollastudenti.R.id.testi;
public class Activity_Quiz extends AppCompatActivity {
SaveData saveData;
String ApiKey;
Dialog dialog;
Gson gson;
Button next_question, previous_question;
int quizID, questionID, trueanswer, useranswer;
int rowID = 1;
String question, filename, mime, image;
SQLiteDatabase db;
TextView viewquestion, question_number, user_email, user_id, quiz_number;
QuizAdapter quizAdapter;
private AllLectureAdapter adapter;
DbProductModel dbProductModel;
List < Quiz_Data > lecture;
RadioGroup my_answer;
NumberPicker numberPicker;
Button start_timer, stop_timer;
MyCountDownTimer myCountDownTimer;
TextView koha;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity__quiz);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(false);
getSupportActionBar().setTitle(Html.fromHtml("<font color='#FFFFFF'><b>QUIZ</b></font>"));
saveData = new SaveData(getApplication());
gson = new GsonBuilder().create();
ApiKey = "bearer " + saveData.getAutoUserToken();
if (!saveData.getQuizStatus().equalsIgnoreCase("start")) {
myCountDownTimer = new MyCountDownTimer(2400000, 1000);
myCountDownTimer.start();
loading();
generate_quiz(ApiKey);
saveData.setQuizStatus("in_progress");
}
question_number = (TextView) findViewById(R.id.questionnumber);
user_email = (TextView) findViewById(R.id.email);
user_id = (TextView) findViewById(R.id.ID);
quiz_number = (TextView) findViewById(testi);
user_email.setText("Email : " + saveData.getAutoUserEmail());
user_id.setText("ID : " + saveData.getAutoUserId() + "");
next_question = (Button) findViewById(R.id.nextbtn);
previous_question = (Button) findViewById(R.id.prevbtn);
viewquestion = (TextView) findViewById(R.id.question);
my_answer = (RadioGroup) findViewById(R.id.useranswer);
final QuizSendModel results = new QuizSendModel();
koha = (TextView) findViewById(R.id.time);
if (rowID > 1 && rowID < 40) {
previous_question.setEnabled(true);
next_question.setEnabled(true);
} else if (rowID == 40) {
next_question.setEnabled(false);
} else if (rowID == 1) {
previous_question.setEnabled(false);
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.gotoquestion);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final Dialog dialog = new Dialog(Activity_Quiz.this);
dialog.setContentView(R.layout.questions);
dialog.setCancelable(true);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
Button shiko = (Button) dialog.findViewById(R.id.shikopyetje);
numberPicker = (NumberPicker) dialog.findViewById(R.id.number_picker);
dialog.show();
/* Window window = dialog.getWindow();
window.setLayout(400, 600);*/
shiko.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
question_number.setText(String.valueOf(numberPicker.getValue()) + "/40");
String[] proj = {
UsersProvider.QUESTION,
UsersProvider.USER_ANSWER
};
String[] args = {
String.valueOf(numberPicker.getValue())
};
Cursor c = getContentResolver().query(UsersProvider.CONTENT_URI, proj, UsersProvider.ID_ROW + " = ?", args, null);
if (c.moveToFirst()) {
do {
viewquestion.setText(c.getString(c.getColumnIndex(UsersProvider.QUESTION)));
String uswanswradio = c.getString(c.getColumnIndex(UsersProvider.USER_ANSWER));
if (uswanswradio == null) {
my_answer.clearCheck();
} else if (uswanswradio.equalsIgnoreCase("0")) {
my_answer.check(R.id.radioJO);
} else if (uswanswradio.equalsIgnoreCase("1")) {
my_answer.check(R.id.radioPO);
}
} while (c.moveToNext());
}
dialog.dismiss();
}
});
}
});
viewquestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Cursor c = getContentResolver().query(UsersProvider.CONTENT_URI, null, null, null, null);
if (c.moveToFirst()) {
do {
/*Toast.makeText(getApplicationContext()," "+c.getString(c.getColumnIndex(UsersProvider.NAME))+", "+c.getString(c.getColumnIndex(UsersProvider.ADDRESS)),Toast.LENGTH_LONG).show();
System.out.println("emri : "+c.getString(c.getColumnIndex(UsersProvider.NAME))+" address : "+c.getString(c.getColumnIndex(UsersProvider.ADDRESS)));*/
results.setId_question(c.getString(c.getColumnIndex(UsersProvider.ID_QUESTION)));
results.setUser_answer(c.getString(c.getColumnIndex(UsersProvider.USER_ANSWER)));
System.out.println("pyetja : " + results.getId_question());
System.out.println("uans : " + results.getUser_answer());
} while (c.moveToNext());
}
}
});
my_answer.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group,
int checkedId) {
if (checkedId == R.id.radioPO) {
useranswer = 1;
} else if (checkedId == R.id.radioJO) {
useranswer = 0;
}
ContentValues values = new ContentValues();
values.put(UsersProvider.USER_ANSWER, useranswer);
String row = String.valueOf(rowID);
String[] whereArgs = {
row
};
getContentResolver().update(UsersProvider.CONTENT_URI, values, UsersProvider.ID_ROW + " =? ", whereArgs);
}
});
previous_question.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
rowID = rowID - 1;
question_number.setText(rowID + "/40");
String[] proj = {
UsersProvider.QUESTION,
UsersProvider.USER_ANSWER
};
String[] args = {
String.valueOf(rowID)
};
Cursor c = getContentResolver().query(UsersProvider.CONTENT_URI, proj, UsersProvider.ID_ROW + " = ?", args, null);
if (c.moveToFirst()) {
do {
viewquestion.setText(c.getString(c.getColumnIndex(UsersProvider.QUESTION)));
String uswanswradio = c.getString(c.getColumnIndex(UsersProvider.USER_ANSWER));
System.out.println("pergjigjeeuserit : " + c.getString(c.getColumnIndex(UsersProvider.USER_ANSWER)));
if (uswanswradio == null) {
my_answer.clearCheck();
} else if (uswanswradio.equalsIgnoreCase("0")) {
my_answer.check(R.id.radioJO);
} else if (uswanswradio.equalsIgnoreCase("1")) {
my_answer.check(R.id.radioPO);
}
} while (c.moveToNext());
}
}
});
next_question.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
my_answer.clearCheck();
rowID = rowID + 1;
question_number.setText(rowID + "/40");
String[] proj = {
UsersProvider.QUESTION,
UsersProvider.USER_ANSWER
};
String[] args = {
String.valueOf(rowID)
};
Cursor c = getContentResolver().query(UsersProvider.CONTENT_URI, proj, UsersProvider.ID_ROW + " = ?", args, null);
if (c.moveToFirst()) {
do {
viewquestion.setText(c.getString(c.getColumnIndex(UsersProvider.QUESTION)));
String uswanswradio = c.getString(c.getColumnIndex(UsersProvider.USER_ANSWER));
if (uswanswradio == null) {
my_answer.clearCheck();
} else if (uswanswradio.equalsIgnoreCase("0")) {
my_answer.check(R.id.radioJO);
} else if (uswanswradio.equalsIgnoreCase("1")) {
my_answer.check(R.id.radioPO);
}
} while (c.moveToNext());
}
}
});
String[] proj = {
UsersProvider.QUESTION
};
String[] args = {
String.valueOf(1)
};
Cursor c = getContentResolver().query(UsersProvider.CONTENT_URI, proj, UsersProvider.ID_ROW + " = ?", args, null);
if (c.moveToFirst()) {
do {
rowID = 1;
viewquestion.setText(c.getString(c.getColumnIndex(UsersProvider.QUESTION)));
} while (c.moveToNext());
}
}
public void generate_quiz(String APIKEY) {
API api = APIClient.getApi(APIKEY);
Call < Quiz > totclient = api.quiz();
totclient.enqueue(new Callback < Quiz > () {
#Override
public void onResponse(Call < Quiz > call, retrofit2.Response < Quiz > response) {
dialog.dismiss();
// Log.d(TAG, "Succes:" + response.body().isError());
JSONObject obj = new JSONObject();
System.out.println("AllLectures:" + gson.toJson(response.body()));
System.out.println("quiz id:" + gson.toJson(response.body().getQuizNumber()));
quiz_number.setText("Testi : " + gson.toJson(response.body().getQuizNumber()));
if (!gson.toJson(response.body()).equalsIgnoreCase("null")) {
if (gson.toJson(response.body().getError()).equalsIgnoreCase("false")) {
ContentValues values = new ContentValues();
getContentResolver().delete(UsersProvider.CONTENT_URI, null, null);
lecture = response.body().getData();
final List < Quiz_Data > movies = response.body().getData();
for (int i = 0; i < movies.size(); i++) {
quizID = response.body().getQuizNumber();
questionID = response.body().getData().get(i).getId();
question = response.body().getData().get(i).getQuestion();
trueanswer = response.body().getData().get(i).getTrueAnswer();
filename = response.body().getData().get(i).getOriginalFilename();
mime = response.body().getData().get(i).getMime();
image = response.body().getData().get(i).getImage();
values.put(UsersProvider.QUESTION, question);
values.put(UsersProvider.ID_ROW, i + 1);
values.put(UsersProvider.ID_QUESTION, questionID);
values.put(UsersProvider.TRUE_ANSWER, trueanswer);
// values.put(UsersProvider.USER_ANSWER,-1);
values.put(UsersProvider.ORIGINAL_FILENAME, filename);
values.put(UsersProvider.MIME, mime);
values.put(UsersProvider.IMAGE, image);
Uri uri = getContentResolver().insert(UsersProvider.CONTENT_URI, values);
// Toast.makeText(getApplicationContext(),uri.toString(),Toast.LENGTH_LONG).show();
System.out.println("URI :" + uri);
}
} else {
}
} else {
Toast.makeText(getApplicationContext(), "Sesioni juaj ka skaduar ju duhet te rilogoheni", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call < Quiz > call, Throwable t) {
dialog.dismiss();
}
});
}
public void loading() {
dialog = new MaterialDialog.Builder(Activity_Quiz.this)
.title("Duke hyre ne sistem!")
.content("Ju lutem prisni...")
.progress(true, 0)
.show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//handle the click on the back arrow click
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onTick(long millisUntilFinished) {
int progress = (int)(millisUntilFinished / 10000);
koha.setText("" + String.format("%d : %d",
TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished),
TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))));
}
#Override
public void onFinish() {
//finish();
saveData.setQuizStatus("start");
Toast.makeText(getApplicationContext(), "Koha mbaroi", Toast.LENGTH_LONG).show();
}
}
}
Thank You!
Your buttons' states are only updated once since the logic is in onCreate.
Consider transferring that logic into a function and call it in the button's onClick handler after updating the rowID.
For example
private void updateButtonState() {
if (rowID > 1 && rowID < 40) {
previous_question.setEnabled(true);
next_question.setEnabled(true);
} else if (rowID == 40) {
next_question.setEnabled(false);
} else if (rowID == 1) {
previous_question.setEnabled(false);
}
}
And in your onClick
#Override
public void onClick(View v) {
rowID = rowID - 1; // + 1 if next button
updateButtonState();
...
}

How to Censored Bad Words / Offensive Words in Android Studio [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
i'm developing an Android Social app in Android Studio
Can anyone know How to filter bad words / offensive words when posting a new status.
For Example i post something bad words and offensive it will turn to like this "****" also when i post many words it will turn like this "i will hit your ***** right now"
please if you know how to i really need it
Thank you in Advance.
This is my PublishingActivity.java Code
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.iscooldev.socialnetwork.R;
import com.iscooldev.socialnetwork.api.APIService;
import com.iscooldev.socialnetwork.api.GlobalAPI;
import com.iscooldev.socialnetwork.api.PostsAPI;
import com.iscooldev.socialnetwork.api.UsersAPI;
import com.iscooldev.socialnetwork.app.AppConst;
import com.iscooldev.socialnetwork.data.LocationModel;
import com.iscooldev.socialnetwork.data.ResponseModel;
import com.iscooldev.socialnetwork.data.userItem;
import com.iscooldev.socialnetwork.helpers.CacheManager;
import com.iscooldev.socialnetwork.helpers.CropSquareTransformation;
import com.iscooldev.socialnetwork.helpers.FilePath;
import com.iscooldev.socialnetwork.helpers.GPSHelper;
import com.iscooldev.socialnetwork.helpers.M;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.picasso.Picasso;
import com.thin.downloadmanager.DownloadRequest;
import com.thin.downloadmanager.ThinDownloadManager;
import java.io.File;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedFile;
public class PublishActivity extends AppCompatActivity implements OnClickListener, DialogInterface.OnClickListener {
public Intent mIntent;
public LinearLayoutManager layoutManager;
EditText insertedLink;
private ImageView mImagePreview;
private ImageButton addPhoto;
private ImageButton sendStatus;
private ImageButton changePrivacy;
private EditText statusInput;
private TextView profileName, postPrivacy;
private ImageView profilePicture;
private String privacy = "public";
private String statusValue = null;
private String linkValue = null;
private Uri imageUriValue = null;
private LinearLayout urlPreviewLayout;
private TextView urlValuePreview;
private TextView placeValuePreview;
private LinearLayout placePreviewLayout;
private String placeValue = null;
private ThinDownloadManager downloadManager;
private CacheManager mCacheManager;
private Gson mGson;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (M.getToken(this) == null) {
Intent mIntent = new Intent(this, LoginActivity.class);
startActivity(mIntent);
finish();
} else {
mCacheManager = CacheManager.getInstance(this);
mGson = new Gson();
setContentView(R.layout.activity_publish);
initializeView();
if (getIntent().hasExtra(Intent.EXTRA_SUBJECT)) {
setStatusValue(getIntent().getExtras().get(Intent.EXTRA_SUBJECT).toString());
}
if (getIntent().hasExtra(Intent.EXTRA_TEXT)) {
String text = getIntent().getExtras().get(Intent.EXTRA_TEXT).toString();
if (M.isValidUrl(text)) {
setLinkValue(text);
} else {
setStatusValue(text);
}
}
if (getIntent().hasExtra(Intent.EXTRA_STREAM)) {
setImageUriValue((Uri) getIntent().getExtras().get(Intent.EXTRA_STREAM));
M.L(getIntent().getType());
}
getUser();
}
}
public void initializeView() {
downloadManager = new ThinDownloadManager(AppConst.DOWNLOAD_THREAD_POOL_SIZE);
addPhoto = (ImageButton) findViewById(R.id.addPhoto);
sendStatus = (ImageButton) findViewById(R.id.sendStatus);
changePrivacy = (ImageButton) findViewById(R.id.changePrivacy);
mImagePreview = (ImageView) findViewById(R.id.imagePreview);
statusInput = (EditText) findViewById(R.id.statusEdittext);
profilePicture = (ImageView) findViewById(R.id.postOwnerImage);
profileName = (TextView) findViewById(R.id.postOwnerName);
postPrivacy = (TextView) findViewById(R.id.postPrivacy);
TextView removeLink = (TextView) findViewById(R.id.removeLink);
TextView removePlace = (TextView) findViewById(R.id.removePlace);
ImageButton addPlace = (ImageButton) findViewById(R.id.addPlace);
ImageButton addLink = (ImageButton) findViewById(R.id.addLink);
placePreviewLayout = (LinearLayout) findViewById(R.id.placePreviewLayout);
placeValuePreview = (TextView) findViewById(R.id.placeValuePreview);
urlPreviewLayout = (LinearLayout) findViewById(R.id.urlPreviewLayout);
urlValuePreview = (TextView) findViewById(R.id.urlValuePreview);
sendStatus.setOnClickListener(this);
addPhoto.setOnClickListener(this);
changePrivacy.setOnClickListener(this);
addPlace.setOnClickListener(this);
addLink.setOnClickListener(this);
removePlace.setOnClickListener(this);
removeLink.setOnClickListener(this);
//including toolbar and enabling the home button
Toolbar toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle(getString(R.string.title_publish));
}
private void getUser() {
if (M.isNetworkAvailable(this)) {
UsersAPI mUsersAPI = APIService.createService(UsersAPI.class, M.getToken(this));
mUsersAPI.getUser(0, new Callback<userItem>() {
#Override
public void success(userItem user, retrofit.client.Response response) {
try {
mCacheManager.write(mGson.toJson(user), "Profile-0.json");
updateView(user);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void failure(RetrofitError error) {
}
});
} else {
try {
updateView((userItem) mGson.fromJson(mCacheManager.readString("Profile-0.json"), new TypeToken<userItem>() {
}.getType()));
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void updateView(userItem user) {
if (user.getName() != null) {
profileName.setText(user.getName());
} else {
profileName.setText(user.getUsername());
}
if (getFilePath(user.getPicture()) != null) {
Picasso.with(getApplicationContext())
.load(getFilePath(user.getPicture()))
.transform(new CropSquareTransformation())
.placeholder(R.drawable.image_holder)
.error(R.drawable.image_holder)
.into(profilePicture);
} else {
Picasso.with(getApplicationContext())
.load(AppConst.IMAGE_PROFILE_URL + user.getPicture())
.transform(new CropSquareTransformation())
.placeholder(R.drawable.image_holder)
.error(R.drawable.image_holder)
.into(profilePicture);
downloadFile(AppConst.IMAGE_PROFILE_URL + user.getPicture(), user.getPicture());
}
}
private void downloadFile(String url, String hash) {
if (getFilePath(hash) == null) {
Uri downloadUri = Uri.parse(url);
Uri destinationUri = Uri.parse(M.getFilePath(getApplicationContext(), hash));
DownloadRequest downloadRequest = new DownloadRequest(downloadUri)
.setDestinationURI(destinationUri);
downloadManager.add(downloadRequest);
}
}
private String getFilePath(String hash) {
return M.filePath(getApplicationContext(), hash);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == AppConst.SELECT_PICTURE) {
setImageUriValue(data.getData());
}
}
}
#Override
public void onClick(final View v) {
if (v.getId() == R.id.removePlace) {
setPlaceValue(null);
} else if (v.getId() == R.id.removeLink) {
setLinkValue(null);
} else if (v.getId() == R.id.addPlace) {
final GPSHelper mGpsHelper = new GPSHelper(this);
if (mGpsHelper.canGetLocation()) {
GlobalAPI mGlobalAPI = APIService.createService(GlobalAPI.class, M.getToken(this));
mGlobalAPI.getCurrentPlace(mGpsHelper.getLatitude(), mGpsHelper.getLongitude(), new Callback<LocationModel>() {
#Override
public void success(LocationModel location, retrofit.client.Response response) {
if (location.isStatus()) {
setPlaceValue(location.getAddress());
} else {
mGpsHelper.showSettingsAlert();
}
}
#Override
public void failure(RetrofitError error) {
mGpsHelper.showSettingsAlert();
}
});
} else {
mGpsHelper.showSettingsAlert();
}
} else if (v.getId() == R.id.addLink) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(getString(R.string.Insert_a_link));
insertedLink = new EditText(this);
insertedLink.setText("http://");
alert.setView(insertedLink);
alert.setPositiveButton(getString(R.string.ok), this);
alert.setNegativeButton(getString(R.string.cancel), this);
alert.show();
} else if (v.getId() == addPhoto.getId()) {
launchImageChooser();
} else if (v.getId() == sendStatus.getId()) {
String statusText = statusInput.getText().toString().trim();
if (!statusText.isEmpty()) {
setStatusValue(statusText);
}
if (getStatusValue() == null && getImageUriValue() == null && getLinkValue() == null) {
M.T(v,
getString(R.string.Error_empty_post));
} else {
PostsAPI mPostsAPI = APIService.createService(PostsAPI.class, M.getToken(this));
TypedFile image = null;
if (getImageUriValue() != null) {
image = new TypedFile("image/jpg", new File(FilePath.getPath(this, getImageUriValue())));
}
M.showLoadingDialog(this);
mPostsAPI.publishPost(image, getStatusValue(), getLinkValue(), getPlaceValue(), privacy, new Callback<ResponseModel>() {
#Override
public void success(ResponseModel responseModel, Response response) {
M.hideLoadingDialog();
M.T(v, responseModel.getMessage());
if (responseModel.isDone()) {
startActivity(new Intent(PublishActivity.this, MainActivity.class));
finish();
}
}
#Override
public void failure(RetrofitError error) {
M.hideLoadingDialog();
M.T(v, getString(R.string.ServerError));
}
});
}
} else if (v.getId() == changePrivacy.getId()) {
if (privacy.equals("public")) {
postPrivacy.setText(R.string.privatePrivacy);
privacy = "private";
M.T(v, getString(R.string.changed_to_private));
} else {
postPrivacy.setText(R.string.publicPrivacy);
privacy = "public";
M.T(v, getString(R.string.changed_to_public));
}
}
}
private void launchImageChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(
Intent.createChooser(intent, "Choose An Image"),
AppConst.SELECT_PICTURE);
}
#Override
public void onClick(DialogInterface dialog, int which) {
String Link = insertedLink.getText().toString();
if (!Link.equals("http://") && !Link.equals("")) {
setLinkValue(Link);
}
}
public String getPlaceValue() {
return placeValue;
}
public void setPlaceValue(String placeValue) {
if (placeValue != null) {
if (placePreviewLayout.getVisibility() != View.VISIBLE) {
placePreviewLayout.setVisibility(View.VISIBLE);
placeValuePreview.setText(placeValue);
}
} else {
if (placePreviewLayout.getVisibility() != View.GONE) {
placePreviewLayout.setVisibility(View.GONE);
placeValuePreview.setText("");
}
}
this.placeValue = placeValue;
}
public Uri getImageUriValue() {
return imageUriValue;
}
public void setImageUriValue(Uri imageUriValue) {
this.imageUriValue = imageUriValue;
mImagePreview.setImageURI(imageUriValue);
if (mImagePreview.getVisibility() != View.VISIBLE) {
mImagePreview.setVisibility(View.VISIBLE);
}
}
public String getLinkValue() {
return linkValue;
}
public void setLinkValue(String linkValue) {
if (linkValue != null) {
if (urlPreviewLayout.getVisibility() != View.VISIBLE) {
urlPreviewLayout.setVisibility(View.VISIBLE);
urlValuePreview.setText(linkValue);
}
} else {
if (urlPreviewLayout.getVisibility() != View.GONE) {
urlPreviewLayout.setVisibility(View.GONE);
urlValuePreview.setText("");
}
}
this.linkValue = linkValue;
}
public String getStatusValue() {
return statusValue;
}
public void setStatusValue(String statusValue) {
String statusInputValue = statusInput.getText().toString().trim();
if (!statusValue.equals(statusInputValue)) {
String finalStatus;
if (TextUtils.isEmpty(statusInputValue)) {
finalStatus = statusValue;
} else {
finalStatus = statusInputValue + " " + statusValue;
}
statusInput.setText(finalStatus);
this.statusValue = finalStatus;
} else {
this.statusValue = statusValue;
}
}
}
Suppose you have an input string s and the list of words you want to replace by asterisks:
String s = "i will hit your head right now";
List<String> words = Arrays.asList("head", "now"); // suppose these words are offensive
You just iterate over list of offensive words, looking if input string contains one, and perform a replacement. The simplest way to do this is by using regex:
for (String word : words) {
Pattern rx = Pattern.compile("\\b" + word + "\\b", Pattern.CASE_INSENSITIVE);
s = rx.matcher(s).replaceAll(new String(new char[word.length()]).replace('\0', '*'));
}
// s: i will hit your **** right ***
I've added \\b at the front and end of regex pattern to match just whole words (i. e. "head" will be processed, "header" will not). And this piece:
new String(new char[n]).replace('\0', c)
constructs a new string of n chars c.
After that, use resulting s wherever you need.
It is a basic about java, not android related. A way to do this is you make a list of your bad words and replace it from the string that user input. Refer to example below
String userInput = "this is an example of some bad words";
ArrayList<String> badWords = new ArrayList<>();
badWords.add("some");
badWords.add("bad");
badWords.add("words");
for (int i = 0; i < badWords.size(); i++) {
String badWord = badWords.get(i);
if(userInput.toLowerCase().contains(badWord)){
userInput = userInput.replace(badWord, "*****");
}
}

In AsyncTask, stop making registerReceiver() freeze the app

Since I finally figured out that the registerReceiver() method is usually running on the UI-Thread, I now want to change that. I just need some advice of how I could do that.
How would I be able to change registerReceiver() to stop freezing my app?
My doInBackground() method from the AsyncTask, runs another method that is using the registerReceiver(mReceiver, filter) method (both variables are already defined). But I want to keep seeing my ProgressDialog instead of making the app freezing.
I read about using a Handler and a new Thread, but I need some help there.
Thanks in advance.
Code:
package ch.scs.mod.tools.messagegenerator.business;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.PowerManager;
import android.telephony.SmsManager;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import ch.scs.mod.tools.messagegenerator.R;
import ch.scs.mod.tools.messagegenerator.model.Testcase;
import ch.scs.mod.tools.messagegenerator.model.Testset;
public class ReportActivity extends Activity implements OnClickListener {
private static final String TAG = "ReportActivity";
private TextView title;
private TextView lblReport;
private TextView lblEmail;
private TableLayout tblReport;
private Button btnBack;
private Testset testset;
private Testcase testcase;
private List<Testcase> testcases = new ArrayList<Testcase>();
private String number;
private String apn = "not used";
private String error;
private ArrayList<String> resultarray = new ArrayList<String>();
private ProgressDialog progressdialog;
private boolean running = false;
public enum State {
UNKNOWN, CONNECTED, NOT_CONNECTED
}
private ConnectivityManager mConnMgr;
private PowerManager.WakeLock mWakeLock;
private ConnectivityBroadcastReceiver mReceiver;
private NetworkInfo mNetworkInfo;
private State mState;
private boolean mListening;
private boolean mSending;
private SendMms sendMms = SendMms.getInstance();
private MMSTest myTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.report);
title = (TextView) findViewById(R.id.lblTitle);
lblReport = (TextView) findViewById(R.id.lblReport);
lblEmail = (TextView) findViewById(R.id.lblMmsEmail);
tblReport = (TableLayout) findViewById(R.id.tblReport);
btnBack = (Button) findViewById(R.id.btnBack);
progressdialog = new ProgressDialog(this);
progressdialog.setTitle("Please wait...");
progressdialog.setMessage("Sending...");
progressdialog.setCancelable(false);
Typeface tf = Typeface.createFromAsset(getAssets(),
"fonts/TheSansB_TT4_App.ttf");
title.setTypeface(tf);
lblEmail.setTypeface(tf);
lblReport.setTypeface(tf);
btnBack.setTypeface(tf);
lblEmail.setText(Html
.fromHtml("<a href=\'mailto:mathias.hubacher#swisscom.com\'>mathias.hubacher#swisscom.com</a>"));
lblEmail.setMovementMethod(LinkMovementMethod.getInstance());
btnBack.setOnClickListener(this);
testset = (Testset) this.getIntent().getSerializableExtra("testset");
number = (String) this.getIntent().getStringExtra("number");
lblReport.setText(getResources().getString(R.string.reportText1) + " "
+ number + " " + getResources().getString(R.string.reportText2));
testcases = testset.getTestcases();
resultarray.clear();
// Creating Views for Asynctask
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
HorizontalScrollView hsv = new HorizontalScrollView(this);
sv.setLayoutParams(new ScrollView.LayoutParams(ScrollView.LayoutParams.MATCH_PARENT, getWindowManager().getDefaultDisplay().getHeight()/2));
sv.setVerticalScrollBarEnabled(true);
sv.setHorizontalScrollBarEnabled(true);
sv.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
hsv.setLayoutParams(new HorizontalScrollView.LayoutParams(HorizontalScrollView.LayoutParams.MATCH_PARENT, HorizontalScrollView.LayoutParams.MATCH_PARENT));
hsv.setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
ll.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
ll.setOrientation(LinearLayout.VERTICAL);
for (Testcase testc : testcases) {
TableRow tr = new TableRow(this);
TextView tv = new TextView(this);
TextView tvok = new TextView(this);
TextView tverror = new TextView(this);
tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT));
tv.setText(testc.getName() + " ");
tv.setTextColor(getResources().getColor(R.color.white));
tr.addView(tv);
tvok.setText("Sending...");
tvok.setTextColor(getResources().getColor(R.color.white));
tverror.setText("");
tverror.setTextColor(getResources().getColor(R.color.orange));
tr.addView(tvok);
tr.addView(tverror);
ll.addView(tr);
testc.setTextView(tv);
testc.setTextViewOk(tvok);
testc.setTextViewError(tverror);
}
hsv.addView(ll);
sv.addView(hsv);
tblReport.addView(sv);
myTask = new MMSTest();
myTask.execute();
}
private void createSms(List<Testcase> tcs) {
for (Testcase testc : tcs) {
error = "";
if (!testc.isExecute()) {
resultarray.add(getResources().getString(R.string.notExe));
resultarray.add(error);
} else {
sendSms(number, testc);
if (testc.isSuccsess()) {
resultarray.add(getResources().getString(R.string.ok));
resultarray.add(error);
} else {
resultarray.add(getResources().getString(R.string.failed));
resultarray.add(error);
}
}
testc.setRunning(true);
myTask.onProgressUpdate(resultarray.get(resultarray.size()-2), resultarray.get(resultarray.size()-1));
}
}
private class MMSTest extends AsyncTask<String, String, ArrayList<String>> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mReceiver = new ConnectivityBroadcastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(mReceiver, filter);
// progressdialog.show();
}
#Override
protected ArrayList<String> doInBackground(String... params) {
if (testset.getType().equals("sms")) {
Log.v(TAG, "Testtype SMS");
createSms(testcases);
} else if (testset.getType().equals("mms")) {
Log.v(TAG, "Testtype MMS");
mListening = true;
mSending = false;
mConnMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// mReceiver = new ConnectivityBroadcastReceiver();
apn = (String) ReportActivity.this.getIntent().getStringExtra("apn");
startMms();
} else {
lblReport.setText("Error Testset Type not valid");
}
return resultarray;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
for (Testcase testc : testcases) {
if (testc.getRunning()) {
TextView tvok = testc.getTextViewOk();
TextView tverror = testc.getTextViewError();
if (testc.isExecute()) {
if (testc.isSuccsess()) {
tvok.setText(values[0]);
tvok.setTextColor(getResources().getColor(R.color.green));
tverror.setText(values[1]);
tverror.setTextColor(getResources().getColor(R.color.orange));
}
else {
tvok.setText(values[0]);
tvok.setTextColor(getResources().getColor(R.color.red));
tverror.setText(values[1]);
tverror.setTextColor(getResources().getColor(R.color.white));
}
}
else {
tvok.setText(values[0]);
tvok.setTextColor(getResources().getColor(R.color.red));
tverror.setText(values[1]);
tverror.setTextColor(getResources().getColor(R.color.white));
}
testc.setRunning(false);
break;
}
}
}
#Override
protected void onPostExecute(ArrayList<String> result) {
super.onPostExecute(result);
// int r = 0;
// for (Testcase testc : testcases) {
// TextView tvok = testc.getTextViewOk();
// TextView tverror = testc.getTextViewError();
// if (testc.isExecute()) {
// if (testc.isSuccsess()) {
// tvok.setText(result.get(r));
// tvok.setTextColor(getResources().getColor(R.color.green));
// tverror.setText(result.get(r+1));
// tverror.setTextColor(getResources().getColor(R.color.orange));
// }
// else {
// tvok.setText(result.get(r));
// tvok.setTextColor(getResources().getColor(R.color.red));
// tverror.setText(result.get(r+1));
// tverror.setTextColor(getResources().getColor(R.color.white));
// }
// }
// else {
// tvok.setText(result.get(r));
// tvok.setTextColor(getResources().getColor(R.color.red));
// tverror.setText(result.get(r+1));
// tverror.setTextColor(getResources().getColor(R.color.white));
// }
// r = r + 2;
// }
// progressdialog.dismiss();
}
}
private void sendMms() {
int responseCode=0;
for (Testcase testc : testcases) {
error = "";
if (testc.isExecute()) {
File file = new File(Environment.getExternalStorageDirectory(), ".MODTest/" + testc.getContentFile());
if (file.exists()) {
if (file.length() > 300000) {
Log.v(TAG, "File Length="+ Long.toString(file.length()));
error=getResources().getString(R.string.warningFileSize);
}
responseCode = sendMms.startMms(testc.getSubject(), number, apn, testc.getContentFile(), testc.getContentType(), getApplicationContext());
Log.v(TAG,"Test: "+ testc.getName() + " / Response code: " + Integer.toString(responseCode));
if (responseCode == 200) {
testc.setSuccsess(true);
responseCode = 0;
} else {
testc.setSuccsess(false);
error =Integer.toString(responseCode);
}
} else {
testc.setSuccsess(false);
error =getResources().getString(R.string.errorNoFile);
}
if (testc.isSuccsess()) {
resultarray.add(getResources().getString(R.string.ok) + " ");
resultarray.add(error);
} else {
resultarray.add(getResources().getString(R.string.failed) + " ");
resultarray.add(error);
}
} else {
resultarray.add(getResources().getString(R.string.notExe));
resultarray.add(error);
}
testc.setRunning(true);
myTask.onProgressUpdate(resultarray.get(resultarray.size()-2), resultarray.get(resultarray.size()-1));
}
endMmsConnectivity();
mSending = false;
mListening = false;
}
public void startMms() {
for (Testcase tcs : testcases) {
testcase = tcs;
number = number + "/TYPE=PLMN";
// IntentFilter filter = new IntentFilter();
// filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
// registerReceiver(mReceiver, filter);
try {
// Ask to start the connection to the APN. Pulled from Android
// source code.
int result = beginMmsConnectivity();
Log.v(TAG, "Result= " + Integer.toString(result));
if (result != PhoneEx.APN_ALREADY_ACTIVE) {
Log.v(TAG, "Extending MMS connectivity returned " + result
+ " instead of APN_ALREADY_ACTIVE");
// Just wait for connectivity startup without
// any new request of APN switch.
return;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void sendSms(String nr, Testcase tc) {
if (!tc.getBody().equals("")) {
SmsManager sm = SmsManager.getDefault();
sm.getDefault().sendTextMessage(nr, null, tc.getBody(), null, null);
tc.setSuccsess(true);
} else {
tc.setSuccsess(false);
error = getResources().getString(R.string.errorEmptySms);
}
}
#Override
public void onClick(View v) {
if (v.equals(findViewById(R.id.btnBack))) { // Wenn Button zurück
// geklickt wird
Intent startMmsTest = new Intent(ReportActivity.this,
StartActivity.class);
startActivity(startMmsTest);
}
}
protected void endMmsConnectivity() {
// End the connectivity
try {
Log.v(TAG, "endMmsConnectivity");
if (mConnMgr != null) {
mConnMgr.stopUsingNetworkFeature(
ConnectivityManager.TYPE_MOBILE,
PhoneEx.FEATURE_ENABLE_MMS);
}
} finally {
releaseWakeLock();
}
}
protected int beginMmsConnectivity() throws IOException {
// Take a wake lock so we don't fall asleep before the message is
// downloaded.
createWakeLock();
int result = mConnMgr.startUsingNetworkFeature(
ConnectivityManager.TYPE_MOBILE, PhoneEx.FEATURE_ENABLE_MMS);
Log.v(TAG, "beginMmsConnectivity: result=" + result);
switch (result) {
case PhoneEx.APN_ALREADY_ACTIVE:
case PhoneEx.APN_REQUEST_STARTED:
acquireWakeLock();
return result;
}
throw new IOException("Cannot establish MMS connectivity");
}
private synchronized void createWakeLock() {
// Create a new wake lock if we haven't made one yet.
if (mWakeLock == null) {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"MMS Connectivity");
mWakeLock.setReferenceCounted(false);
}
}
private void acquireWakeLock() {
// It's okay to double-acquire this because we are not using it
// in reference-counted mode.
mWakeLock.acquire();
}
private void releaseWakeLock() {
// Don't release the wake lock if it hasn't been created and acquired.
if (mWakeLock != null && mWakeLock.isHeld()) {
mWakeLock.release();
}
}
private class ConnectivityBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
int responseCode;
String action = intent.getAction();
if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)
|| mListening == false) {
Log.w(TAG, "onReceived() called with " + mState.toString()
+ " and " + intent);
return;
}
boolean noConnectivity = intent.getBooleanExtra(
ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (noConnectivity) {
mState = State.NOT_CONNECTED;
} else {
mState = State.CONNECTED;
}
mNetworkInfo = (NetworkInfo) intent
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
// mOtherNetworkInfo = (NetworkInfo) intent
// .getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
// mReason =
// intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
// mIsFailover =
// intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER,
// false);
// Check availability of the mobile network.
if (mNetworkInfo == null) {
/**
* || (mNetworkInfo.getType() !=
* ConnectivityManager.TYPE_MOBILE)) {
*/
Log.v(TAG, " type is not TYPE_MOBILE_MMS, bail");
return;
}
if (!mNetworkInfo.isConnected()) {
Log.v(TAG, " TYPE_MOBILE_MMS not connected, bail");
return;
} else {
Log.v(TAG, "connected..");
if (mSending == false) {
mSending = true;
sendMms();
}
}
}
}
}
Move it to onProgressUpdate() method, or better , onPostExecute()/onPreExecuteMethod() depending on your need.
These methods run on UI thread and not on the new thread creetaed by the Asynctask

JSON parser can't run

My application cannot read data from a server, but I can't find the error in my code or its error log. In fact, after checking my API, the link works fine. INTERNET and WRITE_EXTERNAL_STORAGE permission are already set in the manifest.
My code:
package com.berthojoris.bacaberita;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.berthojoris.bacaberita.adapter.BeritaAdapter;
import com.berthojoris.bacaberita.bean.BeritaBean;
import com.berthojoris.bacaberita.lib.Constants;
import com.berthojoris.bacaberita.lib.ImageLoader;
import com.berthojoris.bacaberita.lib.JSONParser;
import com.berthojoris.bacaberita.lib.Utils;
import com.berthojoris.bacaberita.sqlite.UtilBerita;
public class Berita extends ListActivity {
ProgressDialog dialog;
private static String urlBerita = "http://newapi.bacaberita.com/berita";
public ImageLoader imageLoader;
private JSONParser jParser;
Toast msg;
TextView notfound;
JSONArray contacts = null;
ArrayList<BeritaBean> AmbilDataBean = new ArrayList<BeritaBean>();
BeritaAdapter adapter;
UtilBerita UtilBerita;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialog = new ProgressDialog(this);
UtilBerita = new UtilBerita(this);
imageLoader = new ImageLoader(this.getApplicationContext());
notfound = (TextView) findViewById(R.id.notfound);
notfound.setVisibility(View.GONE);
getListView().setVisibility(View.VISIBLE);
AmbilDataBean = new ArrayList<BeritaBean>();
adapter = new BeritaAdapter(this, AmbilDataBean);
setListAdapter(adapter);
Utils.setPolicyThread();
// Creating JSON Parser Instance
jParser = new JSONParser();
Log.e("Berita Activity", "TOTAL SIZE DATABASE : "
+ UtilBerita.ReadBerita().size());
if (UtilBerita.ReadBerita().size() < 1) {
Log.e("Berita Activity", "DATABASE KOSONG. JALANKAN ASYNC");
new async().execute();
} else {
AmbilDataBean = UtilBerita.ReadBerita();
adapter.setItem(AmbilDataBean);
Log.e("Berita Activity", "DATABASE DIAMBIL");
}
setTimerRefresh();
}// Tutup onCreate
private class async extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
AmbilDataBean = new ArrayList<BeritaBean>();
dialog.setMessage("Please wait...");
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
String jsonContent = jParser.getJSONDataFromUrl(urlBerita);
Log.e("Berita Activity", "PROSES BACKGROUND DIJALANKAN");
return jsonContent;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result.length() > 0) {
dialog.dismiss();
// parsing disini
JSONObject json = null;
try {
json = new JSONObject(result);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(Constants.TAG_ITEM);
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(Constants.TAG_MenuID);
String judul = c.getString(Constants.TAG_Title);
//String img = c.getString(Constants.TAG_Link);
String desk = c.getString(Constants.TAG_Post);
String date = c.getString(Constants.TAG_Created);
BeritaBean mb = new BeritaBean();
mb.setID(id);
mb.setTitle(judul);
//mb.setLink("http://" + img);
mb.setPost(desk);
mb.setCreated(date);
AmbilDataBean.add(mb);
}
adapter.setItem(AmbilDataBean);
Log.e("Berita Activity",
"PROSES SELESAI. DATA AKAN DITAMPILKAN");
} catch (Exception e) {
dialog.dismiss();
Toast.makeText(getBaseContext(),
"Connection Error. Please try again...",
Toast.LENGTH_SHORT).show();
}
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
}
});
} catch (Exception e) {
dialog.dismiss();
Toast.makeText(getBaseContext(),
"Connection Error. Please try again...",
Toast.LENGTH_SHORT).show();
}
} // Tutup if (result.length() > 0)
else {
dialog.dismiss();
Toast.makeText(getBaseContext(),
"Data Not Found. Please try again...",
Toast.LENGTH_SHORT).show();
}
if (AmbilDataBean.size() < 1) {
notfound.setVisibility(View.VISIBLE);
getListView().setVisibility(View.GONE);
} else {
for (BeritaBean bean : AmbilDataBean) {
if (UtilBerita.getDetailWhereID(bean.getID()).getID() == null) {
Log.e("Berita Activity",
"Insert database : " + bean.getID());
UtilBerita.CreateData(bean);
} else {
Log.e("Berita Activity",
"Update database : " + bean.getID());
UtilBerita.UpdateBerita(bean);
}
}
notfound.setVisibility(View.GONE);
getListView().setVisibility(View.VISIBLE);
}
} // Tutup onPostExecute
} // Tutup private class async extends AsyncTask
// =========================================================================================================================
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage(R.string.really_quit)
.setPositiveButton(R.string.yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
finish();
}
}).setNegativeButton(R.string.no, null).show();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
// =========================================================================================================================
// Declare the timer
Timer timer = null;
final Handler handler = new Handler();
public void setTimerRefresh() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
Log.e("Main Activity", "RUNNING TASK...");
new async().execute();
}
});
}
}, 1000 * 60 * 1, 1000 * 25);
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (timer != null) {
timer.cancel();
timer = null;
}
if (UtilBerita != null)
UtilBerita.Close();
}
}
== UPDATE ==
My Constants class :
package com.berthojoris.bacaberita.lib;
public class Constants {
public static final String TAG_ITEM = "items";
public static final String TAG_MenuID = "Menu_ID";
public static final String TAG_IsDisplay = "IsDisplay";
public static final String TAG_CategoryName = "CategoryName";
public static final String TAG_CategoryID = "Category_ID";
public static final String TAG_ContentID = "Content_ID";
public static final String TAG_Title = "Title";
public static final String TAG_Post = "Post";
public static final String TAG_Link = "Link";
public static final String TAG_Meta = "Meta";
public static final String TAG_CreatedBy = "CreatedBy";
public static final String TAG_Created = "Created";
public static final String TAG_StartDisplay = "StartDisplay";
public static final String TAG_Counter = "counter";
}
You have to retrieve jsonArray from the jsonObject items. But in your code you have not used items anywhere. Try this way:
String jsonStr = new ConnectionService().connectionGet("http://newapi.bacaberita.com/berita","");
JSONObject jsonObject = new JSONObject(jsonStr);
System.out.println("..........JSON OBJECT.............");
System.out.println(jsonObject); // full json Object
JSONArray jsonArray = jsonObject.getJSONArray("items");
System.out.println("..........JSON ARRAY PARSING.............");
for(int i=0;i<jsonArray.length();i++)
{
String menu_id = jsonArray.getJSONObject(i).getString("Menu_ID");
String is_display = jsonArray.getJSONObject(i).getString("IsDisplay");
System.out.println("MENU_ID: "+menu_id);
System.out.println("IsDisplay: "+is_display);
}
The methods used in above example are as follows:
public static String connectionGet(String url, String parameter) throws MalformedURLException, ProtocolException, IOException {
URL url1 = new URL(url);
HttpURLConnection request1 = (HttpURLConnection) url1.openConnection();
request1.setRequestMethod("GET");
request1.connect();
String responseBody = convertStreamToString(request1.getInputStream());
return responseBody;
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
} catch (IOException e) {
} finally {
try {
is.close();
} catch (IOException e) {
}
}
return sb.toString();
}

Categories

Resources