This is my activity where I display my data from an online database. What I'm trying to do is - when clicking an item inside the listview it can delete an item. But it is not working, can you help me?.
Here is my code:
ListOfOrders.java
package com.system.receivingoforder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.system.receivingoforder.app.AppConfig;
import com.system.receivingoforder.app.AppController;
public class ListOfOrders extends ListActivity{
private static final String TAG = RegisterActivity.class.getSimpleName();
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
Typeface customFont;
TextView list_of_orders_txt;
ListView listView1;
SimpleAdapter adapter;
String[] table = new String[9999];
String desc[] = new String[9999];
String price[] = new String[9999];
String quantity[] = new String[9999];
String num, info;
int x;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listoforders);
customFont = Typeface.createFromAsset(getAssets(), "fonts/EraserRegular.ttf");
list_of_orders_txt = (TextView)findViewById(R.id.list_of_orders_tv);
list_of_orders_txt.setTypeface(customFont);
adapter = new SimpleAdapter( this, list, R.layout.listoforders_items,
new String[] {"title","subtitle"},
new int[] {R.id.loo_tablenumber,R.id.loo_itemquantity} );
getOrderDetails();
}
#Override
public void finish() {
// TODO Auto-generated method stub
super.finish();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
deleteOrder(table[position], desc[position], price[position], quantity[position]);
}
public void getOrderDetails() {
// Tag used to cancel the request
String tag_string_req = "req_register";
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
JSONObject user = jObj.getJSONObject("user");
JSONArray tablenumarray = jObj.getJSONArray("tablearray");
JSONArray descarray = jObj.getJSONArray("descarray");
JSONArray pricearray = jObj.getJSONArray("pricearray");
JSONArray quantityarray = jObj.getJSONArray("quantityarray");
num = user.getString("prows");
x = Integer.parseInt(num);
HashMap<String,String> map = new HashMap<String,String>();
for(int i=0; i<x; i++) {
table[i] = tablenumarray.getString(i);
//treatment[i] = treatmentarray.getString(i);
desc[i] = descarray.getString(i);
price[i] = pricearray.getString(i);
quantity[i] = quantityarray.getString(i);
}
for(int i=0; i<x; i++) {
info = "Description: " + desc[i].toString() + " \n" + "Price: " + price[i].toString() + " \n" + "Quantity: " + quantity[i].toString();
map = new HashMap<String,String>();
map.put("title", "Table Number: " + table[i].toString());
map.put("subtitle", info);
list.add(map);
}
setListAdapter(adapter);
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "orderinfo");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
//delete Order
private void deleteOrder(final String tablenum, final String desc, final String price, final String quantity) {
// Tag used to cancel the request
String tag_string_req = "req_registerpatient";
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
Toast.makeText(getApplicationContext(), "Order Deleted", Toast.LENGTH_LONG).show();
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "deleteorder");
params.put("tablenum", tablenum);
params.put("desc", desc);
params.put("price", price);
params.put("quantity", quantity);
//params.remove("tablenum");
//params.remove("desc");
//params.remove("price");
//params.remove("quantity");
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
}
RegisterActivity.java
package com.system.receivingoforder;
import com.system.receivingoforder.app.AppConfig;
import com.system.receivingoforder.app.AppController;
import com.system.receivingoforder.helper.SQLiteHandler;
import com.system.receivingoforder.helper.SessionManager;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
public class RegisterActivity extends Activity {
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnRegister;
private EditText inputFullName;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
private SQLiteHandler db;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// SQLite database handler
db = new SQLiteHandler(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn()) {
// User is already logged in. Take him to main activity
}
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
if (!name.isEmpty() && !email.isEmpty() && !password.isEmpty()) {
registerUser(name, email, password);
} else {
Toast.makeText(getApplicationContext(),
"Please enter your details!", Toast.LENGTH_LONG)
.show();
}
}
});
// Link to Login Screen
}
/**
* Function to store user in MySQL database will post params(tag, name,
* email, password) to register url
* */
private void registerUser(final String name, final String email,
final String password) {
// Tag used to cancel the request
String tag_string_req = "req_register";
pDialog.setMessage("Registering ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST,
AppConfig.URL_REGISTER, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
if (!error) {
// User successfully stored in MySQL
// Now store the user in sqlite
String uid = jObj.getString("uid");
JSONObject user = jObj.getJSONObject("user");
String name = user.getString("name");
String email = user.getString("email");
String created_at = user
.getString("created_at");
// Inserting row in users table
db.addUser(name, email, uid, created_at);
// Launch login activity
} else {
// Error occurred in registration. Get the error
// message
String errorMsg = jObj.getString("error_msg");
Toast.makeText(getApplicationContext(),
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("tag", "register");
params.put("name", name);
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog() {
if (!pDialog.isShowing())
pDialog.show();
}
private void hideDialog() {
if (pDialog.isShowing())
pDialog.dismiss();
}
}
listoforders.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/greenboard_background" >
<TextView
android:id="#+id/list_of_orders_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="45dp"
android:text="#string/list_of_orders"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="35sp" />
<ListView
android:id="#+id/android:list"
android:layout_width="543dp"
android:layout_height="800dp"
android:layout_below="#+id/list_of_orders_tv"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
listoforders_items.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/loo_tablenumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="#string/table_no"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30sp" />
<TextView
android:id="#+id/loo_itemquantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/loo_tablenumber"
android:text="#string/item_quantity"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="30sp" />
</RelativeLayout>
You use arraylist so you can use arrayList.remove(position) and after that you just need to add adapter.notifyDataSetChanged();
Related
I am making an attendance app on android studio, but whenever I try to log in using correct credentials I need to click twice on the login button to move forward to the next activity. I tried Asynctasks because of its background thread, after the same result I just reverted back
So, at first click nothing happens but as soon as please wait dialog box disappears and if I click like in under a second or two then it moves to the next activity.
clicking on login fetches some data from the server after the server has validated that the login exists and is correct. when data is received then the new activity is supposed to start since that received data will be shown in the next activity. (i have a list that is checked if it has data then it moves forward)
Login Activity code:
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
//sign up and login button
private Button btnSignUp;
private Button btnLogin;
private ProgressDialog progressDialog;
private RequestQueue Queue;
//data URL
private String extractStudentDataURL = "https://asuiot12.000webhostapp.com/checkLoginCredentials.php";
private String extractEnrolmentsDataURL = "https://asuiot12.000webhostapp.com/retrieveEnrolledCoursesData.php";
//editText
private EditText editTextEmail, editTextPassword;
private ConstraintLayout login;
//string variables
public static String inputEmail;
private String inputPassword;
//array list to store enrolled courses data
public static LinkedList<Courses> enrolledCoursesData = new LinkedList();
//static variable
public static StudentData studentData;
//shared preferences to maintain the login status of the user...
public static SharedPreferences sp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login = findViewById(R.id.login_activity);
login.setBackgroundColor(Color.WHITE);
btnSignUp = findViewById(R.id.button_sign_up);
btnLogin = findViewById(R.id.button_login);
// sp = getSharedPreferences("login", MODE_PRIVATE);
editTextEmail = findViewById(R.id.editText_RA_emailAddress);
editTextPassword = findViewById(R.id.editText_RA_password);
//login button listener
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inputEmail = editTextEmail.getText().toString();
inputPassword = editTextPassword.getText().toString();
if (inputEmail.isEmpty()) {
editTextEmail.setError("Email Required");
editTextEmail.requestFocus();
} else if (inputPassword.isEmpty()) {
editTextPassword.setError("Password Required");
editTextPassword.requestFocus();
} else {
enrolledCoursesData.clear();
ExtractData();
}
}
});
//signUp button listener
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, RegistrationActivity.class);
startActivityForResult(intent, 1);
}
});
}
//retrieving data from the server and checking the login credentials
private void ExtractData() {
StringRequest stringRequest = new StringRequest(Request.Method.POST, extractStudentDataURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject data = array.getJSONObject(i);
int success = data.getInt("success");
if (success == 1) {
Long CNIC = data.getLong("CNIC");
String name = data.getString("Full_Name");
String fss = data.getString("FSS");
String regNo = data.getString("Reg_No");
String batch = data.getString("Batch");
String department = data.getString("Department");
int semester = data.getInt("Semester");
Long mobileNo = data.getLong("Mobile_No");
String nationality = data.getString("Nationality");
String MACAddress = data.getString("MAC_Address");
String homeAddress = data.getString("Home_Address");
String email = data.getString("Email");
String loginPassword = data.getString("Login_Password");
String photo = data.getString("Photo");
studentData = new StudentData(new BigInteger(String.valueOf(CNIC)), new BigInteger(String.valueOf(mobileNo))
, semester, name, fss, regNo, batch, department, nationality,
MACAddress, homeAddress, email, loginPassword, photo);
Toast.makeText(MainActivity.this, "Plz wait....", Toast.LENGTH_LONG).show();
// to get data of courses in which student is enrolled
extractDataOfEnrolments(email);
if (!enrolledCoursesData.isEmpty()) {
Intent intent = new Intent(MainActivity.this, CoursesActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("list", enrolledCoursesData);
intent.putExtras(bundle);
startActivity(intent);
}
} else if (success == 0) {
Toast.makeText(MainActivity.this, "Incorrect username or password",
Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error " + error, Toast.LENGTH_SHORT).show();
}
}) {
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", editTextEmail.getText().toString().trim());
params.put("password", editTextPassword.getText().toString().trim());
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
//retrieving data of enrolments from server
private void extractDataOfEnrolments(final String email) {
StringRequest stringRequest = new StringRequest(Request.Method.POST, extractEnrolmentsDataURL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject data = array.getJSONObject(i);
String courseCode = data.getString("Course_Code");
String courseName = data.getString("Course_Name");
Courses courses = new Courses(courseCode, courseName);
enrolledCoursesData.add(courses);
}
} catch (Exception e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "Error " + error, Toast.LENGTH_SHORT).show();
}
}) {
public Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
If layout code or server-side PHP code is required to better understand the question, then please do ask.
You have a misunderstanding as to how threading works.
In your ExtractData method and its onResponse handler, you call extractDataOfEnrolments(), which is itself asynchronous:
// to get data of courses in which student is enrolled
extractDataOfEnrolments(email);
// the list hasn't been filled yet, will be empty!!!
if (!enrolledCoursesData.isEmpty()) {
}
You then immediately inspect the enrolledCoursesData list and start the CoursesActivity if not empty. The extractDataOfEnrolments() has an asynchronous callback (onResponse()) that hasn't completed yet, so the list would be empty.
You might consider moving the startActivity code into extractDataOfEnrolments(), e.g.:
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject data = array.getJSONObject(i);
String courseCode = data.getString("Course_Code");
String courseName = data.getString("Course_Name");
Courses courses = new Courses(courseCode, courseName);
enrolledCoursesData.add(courses);
}
// now your list is populated, so now Ok to startActivity
if (!enrolledCoursesData.isEmpty()) {
Intent intent = new Intent(MainActivity.this, CoursesActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("list", enrolledCoursesData);
intent.putExtras(bundle);
startActivity(intent);
}
} catch (Exception e) {
}
Im going to make a database in php my sql using android studio
but this error is in the way
//Adding request to request queue
AndroidLoginController.getInstance();
addToRequestQueue(strReq, tag_string_req);
}
I receive the error cannot resolve method 'addToRequestQueque(com.android.volley.toolbox.StringRequest,java.lang.String)'
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.example.pjsr.brnp.MainActivity;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import prefs.UserInfo;
import prefs.UserSession;
public class Login extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = Login.class.getSimpleName();
private EditText email, password;
private Button login;
private TextView signup;
private ProgressDialog progressDialog;
private UserSession session;
private UserInfo userInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
email = (EditText) findViewById(R.id.email);
password = (EditText) findViewById(R.id.password);
login = (Button) findViewById(R.id.login);
signup = (TextView) findViewById(R.id.open_signup);
progressDialog = new ProgressDialog(this);
session = new UserSession(this);
userInfo = new UserInfo(this);
if (session.isUserLoggedin()) {
startActivity(new Intent(this, MainActivity.class));
finish();
}
login.setOnClickListener(this);
signup.setOnClickListener(this);
}
private void login(final String email, final String password) {
//Tag used to cancel the request
String tag_string_req = "req_login";
progressDialog.setMessage("Logging in....");
progressDialog.show();
StringRequest strReq = new StringRequest(Request.Method.POST,
Utils.LOGIN_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
try {
JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");
//check for error node in json
if (!error) {
//now store the user in SQLite
JSONObject user = jObj.getJSONObject("user");
String uName = user.getString("username");
String email = user.getString("email");
//Inserting row in users table
userInfo.setEmail(email);
userInfo.setUsername(uName);
session.setLoggedin(true);
startActivity(new Intent(Login.this, MainActivity.class));
finish();
} else {
//error in login, get the error message
String errorMsg = jObj.getString("error_msg");
toast(errorMsg);
}
} catch (JSONException e) {
//json error
e.printStackTrace();
toast("Json error: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Login Error: " + error.getMessage());
toast("Unknown Error occured");
progressDialog.hide();
}
}) {
#Override
protected Map<String, String> getParams() {
//Posting parameters to login url
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
//Adding request to request queue
AndroidLoginController.getInstance();
addToRequestQueue(strReq, tag_string_req);
}
private void toast(String x) {
Toast.makeText(this, x, Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.login:
String uName = email.getText().toString().trim();
String pass = password.getText().toString().trim();
login(uName, pass);
break;
case R.id.open_signup:
startActivity(new Intent(this, SignUp.class));
break;
}
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Login Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
}
addToRequestQueue is a method defined for the volley application controller which seems to be AndroidLoginController in your case. Change the line to
AndroidLoginController.getInstance().addToRequestQueue(strReq,tag_string_req)
This is assuming you have created the singleton using standard volley tutorials or android developer documentation
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hello everyone I m sorry if this has been asked earlier , i have been searching for this solution since past 3 days.I am new in android and php.
I want to know how can i send "jsonArray"(shown below) to my php server and then extract jsonobject values recieved in php.
I have tried jsonarrayrequest and hashmap but was not able to send. Please help.
String url="http://192.168.43.210/jjj.php";
JSONArray list;
RequestQueue requestQueue;
final JSONArray jsonArray=new JSONArray();
for (int i=0;i<valu;i++)
{
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("comptext",smslist.get(i).completeText);
jsonObject.put("amount",smslist.get(i).amount);
jsonObject.put("txntype",smslist.get(i).txnType);
jsonObject.put("party",smslist.get(i).party);
jsonObject.put("from",smslist.get(i).fromNo);
jsonObject.put("datetime",smslist.get(i).dateTime);
jsonArray.put(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
JsonArrayRequest jsonArrayRequest=new JsonArrayRequest(Request.Method.POST, url, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
result.append("Successfully sent");
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}){
protected Map<JSONArray,JSONArray> getparams() throws AuthFailureError{
Map<JSONArray,JSONArray> parameters = new HashMap<JSONArray, JSONArray>();
parameters.put(list,jsonArray);
return parameters;
}
};
requestQueue.add(jsonArrayRequest);
}
});
Use StringRequest instead of JsonArrayRequest for example:
private void register() {
if (!validate()) {
onRegistrationFailed("Registration Failed");
return;
}
final String name = et_username.getText().toString();
final String email = et_email.getText().toString();
final String phone = et_phone.getText().toString();
final String password = et_password.getText().toString();
showDialog();
StringRequest strRequest = new StringRequest(Request.Method.POST, Config.MAIN_URL + Config.REGISTER,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d(TAG, "Register Response: " + response.toString());
hideDialog();
try {
JSONObject jsonObject = new JSONObject(response);
int status = jsonObject.getInt("status");
String msg = jsonObject.getString("message");
if (status == SUCCESS) {
onRegistrationSuccess(name,email);
} else {
onRegistrationFailed(msg);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Registration Error: " + error.getMessage());
hideDialog();
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put(Config.KEY_USERNAME, name);
params.put(Config.KEY_EMAIL, email);
params.put(Config.KEY_PHONE, phone);
params.put(Config.KEY_PASSWORD, password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strRequest);
}
This is working code for login sample. so try this, and change as per your need.
Login.java
package com.example.volleytest;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.HashMap;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
public class Login extends AppCompatActivity{
public static final String LOGIN_URL = "YOUR_URL";
//"http://192.168.1.100/Login/admin.php";
ProgressDialog pDialog;
public static final String KEY_USERNAME="username";
public static final String KEY_PASSWORD="password";
private EditText editTextUsername;
private EditText editTextPassword;
private Button buttonLogin;
private String username;
private String password;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
editTextUsername = (EditText) findViewById(R.id.editTextUsername);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
buttonLogin = (Button) findViewById(R.id.buttonLogin);
buttonLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(isNetworkAvailable()){
userLogin();
}
else
{
showMessageDialog("Error", "Check your Internet Connection..!");
}
}
});
}
private void userLogin() {
username = editTextUsername.getText().toString().trim();
password = editTextPassword.getText().toString().trim();
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
StringRequest stringRequest = new StringRequest(Request.Method.POST, LOGIN_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//JSONArray myJSON= new JSONArray(response);
JSONObject parentObject = new JSONObject(response);
JSONObject childObject = parentObject.getJSONObject("Tracking");
String status = childObject.optString("status");
String type = childObject.optString("type");
//System.out.println("status : " + status);
//System.out.println("Type : " + type);
if(status.trim().equals("success"))
{
pDialog.hide();
showMessageDialog("Login", type + " Login Successfully..!");
}
else
{
pDialog.hide();
showMessageDialog("Login", "No Users/Admin were Found..! ");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
pDialog.hide();
showMessageDialog("JSON Error", "Server Error..! Try after Some Time..!");//e.getMessage());
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error)
{
pDialog.hide();
//showMessageDialog("Login", "Reponse => " + error.toString());
showMessageDialog("Login", "Server Error..! Try after Some Time..!");
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> map = new HashMap<String,String>();
map.put(KEY_USERNAME,username);
map.put(KEY_PASSWORD,password);
return map;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
public void showMessageDialog(String title , String Message)
{
AlertDialog dialog = new AlertDialog.Builder(Login.this)
.setTitle(title)
.setMessage(Message)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
})
.show();
//TextView textView = (TextView) dialog.findViewById(android.R.id.message);
//textView.setTextSize(25);
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService( CONNECTIVITY_SERVICE );
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
login.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="20dp"
android:text="Login Using Volley Library"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Enter Username"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editTextUsername" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Password"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:id="#+id/editTextPassword" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:id="#+id/buttonLogin" />
</LinearLayout>
I've been working with Volley on Android, it seems that I can't really get this particular part working
this is my json
{
"code": 1,
"status": 200,
"data": "bla... bla..."
}
and this is Activity.class
try
{
JSONObject json_response = new JSONObject(response);
String status = json_response.getString("status");
if (status.equals("200"))
{
do something
}
else
{
Toast.makeText(getApplicationContext(), status, Toast.LENGTH_LONG).show();
}
}
it always skips that condition as it doesn't match, and toast print value 200 as a proof that status returns with value and that value is 200
I did try
int status = json_response.getInt("status");
if (status == 200)
which return "JSONException: Value of type java.lang.String cannot be converted to JSONObject", any insights?
Edit:
here is complete LoginActivity.java
package my.sanik.loginandregistration.activity;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request.Method;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import my.sanik.loginandregistration.R;
import my.sanik.loginandregistration.app.AppConfig;
import my.sanik.loginandregistration.app.AppController;
import my.sanik.loginandregistration.helper.SessionManager;
public class LoginActivity extends Activity
{
private static final String TAG = RegisterActivity.class.getSimpleName();
private Button btnLogin;
private Button btnLinkToRegister;
private EditText inputEmail;
private EditText inputPassword;
private ProgressDialog pDialog;
private SessionManager session;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
btnLogin = (Button) findViewById(R.id.btnLogin);
btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
// Progress dialog
pDialog = new ProgressDialog(this);
pDialog.setCancelable(false);
// Session manager
session = new SessionManager(getApplicationContext());
// Check if user is already logged in or not
if (session.isLoggedIn())
{
// User is already logged in. Take him to main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
String email = inputEmail.getText().toString().trim();
String password = inputPassword.getText().toString().trim();
// Check for empty data in the form
if (!email.isEmpty() && !password.isEmpty())
{
// login user
checkLogin(email, password);
}
else
{
// Prompt user to enter credentials
Toast.makeText(getApplicationContext(), "Please enter the credentials!", Toast.LENGTH_LONG).show();
}
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent i = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(i);
finish();
}
});
}
private void checkLogin(final String email, final String password)
{
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
StringRequest strReq = new StringRequest(Method.POST, AppConfig.URL_LOGIN, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try
{
JSONObject json_response = new JSONObject(response);
String status = json_response.getString("status");
if (status.equals("200"))
{
session.setLogin(true);
// Launch main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
else
{
// Error in login. Get the error message
Toast.makeText(getApplicationContext(), "Wrong username or password", Toast.LENGTH_LONG).show();
}
}
catch (JSONException e)
{
// JSON error
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
Log.e(TAG, "Login Error: " + error.getMessage());
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
hideDialog();
}
}) {
#Override
protected Map<String, String> getParams()
{
// Posting parameters to login url
Map<String, String> params = new HashMap<>();
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
private void showDialog()
{
if (!pDialog.isShowing()) pDialog.show();
}
private void hideDialog()
{
if (pDialog.isShowing()) pDialog.dismiss();
}
}
First try to print your response check what is your response say or some extra thing is there or not.
try{
Log.d(TAG, "Json response :" + response);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and then compare with your value.
{
"code": 1,
"status": 200, // Need this
"data": "bla... bla..."
}
Your status is not String format so,
Call this
int getStatus = Integer.parseInt(json_response.getString("status"));
Then
if (getStatus==200)
{
// Your code
}
Note :
You can use getInt directly instead of getString .
Use this class to get json string
ServiceHandler.java
package com.example;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.util.Log;
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public ServiceHandler() {
}
public String makeServiceCall(String url, int method) {
return this.makeMyServiceCall(url, method);
}
public String makeMyServiceCall(String myurl, int method) {
InputStream inputStream = null;
HttpURLConnection urlConnection = null;
try {
/* forming th java.net.URL object */
URL url = new URL(myurl);
urlConnection = (HttpURLConnection) url.openConnection();
/* optional request header */
urlConnection.setRequestProperty("Content-Type", "application/json");
/* optional request header */
urlConnection.setRequestProperty("Accept", "application/json");
/* for Get request */
urlConnection.setRequestMethod("GET");
int statusCode = urlConnection.getResponseCode();
/* 200 represents HTTP OK */
if (statusCode == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
response = convertInputStreamToString(inputStream);
}
} catch (Exception e) {
Log.d("tag", e.getLocalizedMessage());
}
return response;
}
private String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
/* Close Stream */
if (null != inputStream) {
inputStream.close();
}
return result;
}
}
in MainActivty.java
package com.example;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends Activity {
String jsonStr = "";
JSONObject jo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetDatas().execute();
}
class GetDatas extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
ServiceHandler sh = new ServiceHandler();
// put your url here...
// Making a request to url and getting response
jsonStr = sh.makeServiceCall("http://192.168.1.51/sumit/temp.txt",
ServiceHandler.GET);
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
try {
jo = new JSONObject(jsonStr);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (jo.getInt("status") == 200) {
Toast.makeText(getApplicationContext(), "do something",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"" + jo.getInt("status"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Ok if the problem is that either String or Integer is throwing an exception (which I cannot replicate in Android Studio 1.5.1), I recommend you to do this:
try
{
JSONObject json_response = new JSONObject(response);
Object status = json_response.getString("status");
if (json_response.get("status") instanceof Integer)
{
// it's an integer
}
else if (json_response.get("status") instanceof String)
{
// it's a String
} else {
// let's try to find which class is it
Log.e("MYTAG", "status is an instance of "+json_parse.get("status").getClass().getName());
}
} catch (Exception e) {
Log.e("MYTAG", "Error parsing status => "+e.getMessage());
}
Also you can try doing this first:
JSONObject json_response = new JSONObject(response);
String status = json_response.getString("status");
int statint = Integer.parseInt(status);
I hope it helps.
Try with this
if(status.equalsIgnoreCase("200"))
My Recycler view has 2 buttons: REnew and Return. Both are not working.
Understand that Recycler view cannot implement the onclick, so I implemented the same in Adapter. In the Adapter - I added a toast msg to test of if the button onclick is captured, it is not showing.
Can anyone suggest, what's the reason? Let me know if you need to see more code.
Many thanks.
BookListMyAccAdapter.java
package com.androidatc.customviewindrawer;
import android.app.Activity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
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.TextView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import java.util.List;
import cz.msebera.android.httpclient.Header;
public class BookListMyAccAdapter extends RecyclerView.Adapter<BookListMyAccAdapter.PersonViewHolder> {
public static class PersonViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CardView cv;
TextView title;
TextView dueDt;
// ImageView personPhoto;
public Button searchBtn, renewBtn, returnBtn;
PersonViewHolder(View itemView) {
super(itemView);
` itemView.setOnClickListener(this);
cv = (CardView) itemView.findViewById(R.id.cv);
title = (TextView) itemView.findViewById(R.id.title);
dueDt = (TextView) itemView.findViewById(R.id.dueDate);
// personPhoto = (ImageView)itemView.findViewById(R.id.person_photo);
renewBtn = (Button) itemView.findViewById(R.id.renew_button);
returnBtn = (Button) itemView.findViewById(R.id.checkin_button);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.checkin_button:
String barCode = null, patronId = null;
Log.d("TAG", "Success");
Toast.makeText(myActivity.getApplicationContext(), "B4 calling webservice", Toast.LENGTH_LONG).show();
returnBook(barCode, patronId);
break;
case R.id.renew_button:
barCode = null;
patronId = null;
Log.d("TAG", "Success");
Toast.makeText(myActivity.getApplicationContext(), "B4 calling webservice", Toast.LENGTH_LONG).show();
renewBook(barCode, patronId);
break;
}
}}
List<Books> books;
public static Activity myActivity;
BookListMyAccAdapter(List<Books> books, Activity myActivity) {
this.books = books;
this.myActivity = myActivity;
}
#Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
#Override
public PersonViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_my_acc, viewGroup, false);
PersonViewHolder pvh = new PersonViewHolder(v);
return pvh;
}
#Override
public void onBindViewHolder(PersonViewHolder personViewHolder, int i) {
personViewHolder.title.setText(books.get(i).title);
personViewHolder.dueDt.setText(books.get(i).dueOn);
// personViewHolder.personPhoto.setImageResource(books.get(i).photoId);
}
#Override
public int getItemCount() {
return books.size();
}
public static void renewBook(String barCode, String patronId) {
final int DEFAULT_TIMEOUT = 200000 * 1000000000;
try {
// Make RESTful webservice call using AsyncHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
client.setTimeout(DEFAULT_TIMEOUT);
// progress.setMessage("Please Wait...");
// progress.setIndeterminate(false);
// progress.setCancelable(false);
// progress.show();
RequestParams params = new RequestParams();
params.put("barcode", "B1246855");
params.put("patron", "thida");
Toast.makeText(myActivity.getApplicationContext(), "B4 calling webservice", Toast.LENGTH_LONG).show();
client.post(" htt=1", new TextHttpResponseHandler() {
#Override
public void onSuccess(int i, Header[] headers, String response) {
// Toast.makeText(getActivity().getApplicationContext(), "Response: " + response, Toast.LENGTH_LONG).show();
Log.d("TAG", "Success");
}
#Override
public void onFailure(int statusCode, Header[] headers, String response, Throwable error) {
// Toast.makeText(getActivity().getApplicationContext(), "Status code :" + statusCode + "errmsg : " + error.getMessage(), Toast.LENGTH_LONG).show();
// Toast.makeText(getActivity().getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
Log.d("TAG", "Failure");
}
}
);
} catch (Exception e) {
e.printStackTrace();
// Toast.makeText(getActivity().getApplicationContext(), "Exception Caught", Toast.LENGTH_LONG).show();
}
// progress.dismiss();
// Toast.makeText(getActivity().getApplicationContext(), "After calling webservice", Toast.LENGTH_LONG).show();
}
public static void returnBook(String barCode, String patronId) {
final int DEFAULT_TIMEOUT = 200000 * 1000000000;
try {
// Make RESTful webservice call using AsyncHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
client.setTimeout(DEFAULT_TIMEOUT);
// progress.setMessage("Please Wait...");
// progress.setIndeterminate(false);
// progress.setCancelable(false);
// progress.show();
RequestParams params = new RequestParams();
params.put("barcode", "B1246855");
params.put("patron", "thida");
// Toast.makeText(getActivity().getApplicationContext(), "B4 calling webservice", Toast.LENGTH_LONG).show();
client.post("http://43.246855", new AsyncHttpResponseHandler() {
// http://koha-dev.cvpl.com
#Override
public void onSuccess(int i, Header[] headers, byte[] bytes) {
// Toast.makeText(getActivity().getApplicationContext(), "Response: " + headers, Toast.LENGTH_LONG).show();
Log.d("TAG", "Success");
}
#Override
public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
// Toast.makeText(getActivity().getApplicationContext(), "Status code :" + headers + "errmsg : " + throwable.getMessage(), Toast.LENGTH_LONG).show();
// Toast.makeText(getActivity().getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
Log.d("TAG", "Failure");
}
}
);
} catch (Exception e) {
e.printStackTrace();
// Toast.makeText(getActivity().getApplicationContext(), "Exception Caught", Toast.LENGTH_LONG).show();
}
// progress.dismiss();
// Toast.makeText(getActivity().getApplicationContext(), "After calling webservice", Toast.LENGTH_LONG).show();
}
}
RecyclerMyAccFrag.java
package com.androidatc.customviewindrawer;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import cz.msebera.android.httpclient.Header;
public class RecyclerMyAccFrag extends Fragment
// implements View.OnClickListener
{
public List<Books> books;
public RecyclerView rv;
public TextView formatTxt, contentTxt, TitleTxt, PublisherTxt, CreatorTxt, AvailabiltyTxt;
public Button searchBtn,renewBtn, returnBtn;
ProgressDialog progress;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.recycler_my_acc, container, false);
// renewBtn = (Button) rootView.findViewById(R.id.renew_button);
// returnBtn = (Button) rootView.findViewById(R.id.checkin_button);
// renewBtn.setOnClickListener(this);
// returnBtn.setOnClickListener(this);
String response =getArguments().getString("book_xml");
rv=(RecyclerView)rootView.findViewById(R.id.rv);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
rv.setHasFixedSize(true);
// progress = new ProgressDialog(getActivity());
readDetails(response);
initializeAdapter();
return rootView;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(Uri uri);
}
public void initializeData(String[] titles, String [] dueDts, int total){
books = new ArrayList<>();
for(int i = 0;i<total;i++)
{
books.add(new Books(titles[i], dueDts[i]));
// Toast.makeText(getActivity().getApplicationContext(), "Title : " + i +
// " " + titles[i] + " Due Date: " + dueDts[i], Toast.LENGTH_LONG).show();
}
Toast.makeText(getActivity().getApplicationContext(), "Total Number of Books Found:"
+ total , Toast.LENGTH_LONG).show();
}
public void initializeAdapter(){
BookListMyAccAdapter adapter = new BookListMyAccAdapter(books, getActivity());
rv.setAdapter(adapter);
}
// parse XML
public void readDetails(String response) {
DocumentBuilder builder = null;
try {
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource src = new InputSource();
src.setCharacterStream(new StringReader(response));
Document doc = builder.parse(src);
// NodeList nodes1 = doc.getElementsByTagName("title");
src.setCharacterStream(new StringReader(response));
NodeList nodes = doc.getElementsByTagName("date_due_sql");
int cnt = 0;
// String[] titles1 = new String[10000];
String[] titles = new String[10000];
String[] dueDts = new String[10000];
for (int i = 0; i < nodes.getLength(); i++) {
if (nodes.item(i).getTextContent() == "title") {
// titles1[i] = doc.getElementsByTagName("title").item(0).getTextContent();
}
if (nodes.item(i).getTextContent().trim().isEmpty()) {
cnt++;
}
}
Log.e("TAGLOG", "" + cnt);
for (int i = 0; i < nodes.getLength(); i++) {
titles[i] = doc.getElementsByTagName("title").item(i).getTextContent();
dueDts[i] = doc.getElementsByTagName("date_due_sql").item(i).getTextContent();
}
initializeData(titles, dueDts, nodes.getLength());
// Toast.makeText(getActivity().getApplicationContext(), "Total Number of Books Found:"
// + nodes1.getLength() + " " + titles[0], Toast.LENGTH_LONG).show();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(), "No Book Found", Toast.LENGTH_LONG).show();
} finally {
}
}
public void renewBook(String barCode, String patronId)
{
final int DEFAULT_TIMEOUT = 200000 * 1000000000;
try {
// Make RESTful webservice call using AsyncHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
client.setTimeout(DEFAULT_TIMEOUT);
progress.setMessage("Please Wait...");
progress.setIndeterminate(false);
progress.setCancelable(false);
progress.show();
RequestParams params = new RequestParams();
params.put("barcode", "B1246855");
params.put("patron", "thida");
Toast.makeText(getActivity().getApplicationContext(), "B4 calling webservice", Toast.LENGTH_LONG).show();
client.post(" http://koha-ded=1", new TextHttpResponseHandler() {
#Override
public void onSuccess(int i, Header[] headers, String response) {
Toast.makeText(getActivity().getApplicationContext(), "Response: " + response, Toast.LENGTH_LONG).show();
Log.d("TAG", "Success");
}
#Override
public void onFailure(int statusCode, Header[] headers, String response, Throwable error) {
Toast.makeText(getActivity().getApplicationContext(), "Status code :" + statusCode + "errmsg : " + error.getMessage(), Toast.LENGTH_LONG).show();
Toast.makeText(getActivity().getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
Log.d("TAG", "Failure");
}
}
);
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(), "Exception Caught", Toast.LENGTH_LONG).show();
}
progress.dismiss();
Toast.makeText(getActivity().getApplicationContext(), "After calling webservice", Toast.LENGTH_LONG).show();
}
public void returnBook(String barCode, String patronId)
{
final int DEFAULT_TIMEOUT = 200000 * 1000000000;
try {
// Make RESTful webservice call using AsyncHttpClient object
AsyncHttpClient client = new AsyncHttpClient();
client.setTimeout(DEFAULT_TIMEOUT);
progress.setMessage("Please Wait...");
progress.setIndeterminate(false);
progress.setCancelable(false);
progress.show();
RequestParams params = new RequestParams();
params.put("barcode", "B1246855");
params.put("patron", "thida");
Toast.makeText(getActivity().getApplicationContext(), "B4 calling webservice", Toast.LENGTH_LONG).show();
client.post("http:vice46855", new AsyncHttpResponseHandler() {
// http://koha-dev.cvpl.com.sg/cgi-bin/koha/ilsdi.pl?service=RenewLoan&patron_id=1&item_id=1
#Override
public void onSuccess(int i, Header[] headers, byte[] bytes) {
Toast.makeText(getActivity().getApplicationContext(), "Response: " + headers, Toast.LENGTH_LONG).show();
Log.d("TAG", "Success");
}
#Override
public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
Toast.makeText(getActivity().getApplicationContext(), "Status code :" + headers + "errmsg : " + throwable.getMessage(), Toast.LENGTH_LONG).show();
Toast.makeText(getActivity().getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet or remote server is not up and running]", Toast.LENGTH_LONG).show();
Log.d("TAG", "Failure");
}
}
);
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(), "Exception Caught", Toast.LENGTH_LONG).show();
}
progress.dismiss();
Toast.makeText(getActivity().getApplicationContext(), "After calling webservice", Toast.LENGTH_LONG).show();
}}
item_my_acc.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/cv"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/title"
android:layout_gravity="left"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/dueDate"
android:layout_below="#+id/title"
/>
<Button
android:id="#+id/renew_button"
android:layout_alignParentRight="true"
android:text="#string/renew"
android:layout_below="#id/dueDate"
android:layout_width="90dp"
android:layout_height="40dp"
android:layout_gravity="right"/>
<Button
android:id="#+id/checkin_button"
android:layout_alignParentRight="true"
android:text="#string/checkin"
android:layout_below="#id/renew_button"
android:layout_width="90dp"
android:layout_height="40dp"
android:layout_gravity="right"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
I Think you forgot to add the OnClickListener to your View:
public static class PersonViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CardView cv;
TextView title;
TextView dueDt;
public Button searchBtn, renewBtn, returnBtn;
PersonViewHolder(View itemView) {
super(itemView);
cv = (CardView) itemView.findViewById(R.id.cv);
title = (TextView) itemView.findViewById(R.id.title);
dueDt = (TextView) itemView.findViewById(R.id.dueDate);
renewBtn = (Button) itemView.findViewById(R.id.renew_button);
returnBtn = (Button) itemView.findViewById(R.id.checkin_button);
renewBtn.setOnClickListener(this); // <- This lines
returnBtn.setOnClickListener(this); // <- This lines
}
(...)
}
Currently your ViewHolder class is implementing View.OnClickListener. That's not going to help here.
Instead, you need to call setOnClickListener on the individual view objects that you would like to receive clicks. If it's just the whole row, you only need to do the root view for that row.