Onclick button is not working in adapter (Recycler view app) - java

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.

Related

Change screen after successful login? (Android studio)

I've been tasked during my internship to take over someone else's code and work on a project.I am having difficulties trying to navigate to another screen after a successful login.Currently, the code below redirects me back to the original main menu page after a successful login (While a failed login does nothing).
My question is how do I display a toast message saying wrong username/password?
Currently it displays nothing during a failed login.Also, how do I change screens from activity_login.xml to landing_page.xml after a SUCCESSFUL login? What code should I add?
LoginActivity.java :
package com.finchvpn.androidcloudpark;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.Objects;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class LoginActivity extends AppCompatActivity {
private EditText textUsername;
private EditText txtPassword;
private static RestClient restClient = new RestClient();
private SharedPreferences.Editor sharedPreferencesEditor;
#SuppressLint("CommitPrefEdits")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
try {
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
} catch (Exception e) {
}
textUsername = findViewById(R.id.textUsername);
txtPassword = findViewById(R.id.textPassword);
SharedPreferences sharedPreferences = getSharedPreferences("UserInfo", 0);
sharedPreferencesEditor = sharedPreferences.edit();
textUsername.setText(sharedPreferences.getString("textUsername", ""));
txtPassword.setText(sharedPreferences.getString("txtPassword", ""));
}
public static RestClient getRestClient() {
return restClient;
}
public void loginButtonClick(View v) {
if (!textUsername.getText().toString().equals("") && !txtPassword.getText().toString().equals("")) {
apiPostLogin(Constants.ANDROID_KEY + ":" + textUsername.getText().toString() + ":" + txtPassword.getText().toString());
sharedPreferencesEditor.putString("textUsername", textUsername.getText().toString());
sharedPreferencesEditor.putString("txtPassword", txtPassword.getText().toString());
sharedPreferencesEditor.commit();
} else {
Toast.makeText(LoginActivity.this, "NULL", Toast.LENGTH_LONG).show();
}
}
private void apiPostLogin(String data) {
final ProgressDialog progress = new ProgressDialog(this);
progress.setTitle("Logging in");
progress.setMessage("Please wait ...");
progress.setCancelable(false); // disable dismiss by tapping outside of the dialog
progress.show();
Call<ResponseBody> call = getRestClient().getLoginService().postLogin(data);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful() && response.body() != null) {
try {
String data = response.body().string();
JSONObject jsonObject = new JSONObject(data);
Constants.uid = Integer.parseInt(jsonObject.getString("id"));
Constants.username = jsonObject.getString("username");
Constants.email = jsonObject.getString("email");
Constants.credit = jsonObject.getString("credit");
Constants.qr_code = jsonObject.getString("qr_code");
Constants.created_at = jsonObject.getString("created_at");
Constants.updated_at = jsonObject.getString("updated_at");
Toast.makeText(LoginActivity.this, "apiPostLogin onResponse <<<< \r\n\r\n" + jsonObject.toString(), Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
progress.dismiss();
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(LoginActivity.this, "Incorrect username/password, please try again." + t.getMessage(), Toast.LENGTH_LONG).show();
progress.dismiss();
}
});
}
}
First of all, for changing your activity layout you have to change this line of code in the onCreate method:
setContentView(R.layout.activity_login);
Second, to display toast if the login fails, change your apiPostLogin method to:
private void apiPostLogin(String data) {
final ProgressDialog progress = new ProgressDialog(this);
progress.setTitle("Logging in");
progress.setMessage("Please wait ...");
progress.setCancelable(false); // disable dismiss by tapping outside of the dialog
progress.show();
Call<ResponseBody> call = getRestClient().getLoginService().postLogin(data);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful() && response.body() != null) {
try {
String data = response.body().string();
JSONObject jsonObject = new JSONObject(data);
Constants.uid = Integer.parseInt(jsonObject.getString("id"));
Constants.username = jsonObject.getString("username");
Constants.email = jsonObject.getString("email");
Constants.credit = jsonObject.getString("credit");
Constants.qr_code = jsonObject.getString("qr_code");
Constants.created_at = jsonObject.getString("created_at");
Constants.updated_at = jsonObject.getString("updated_at");
Toast.makeText(LoginActivity.this, "apiPostLogin onResponse <<<< \r\n\r\n" + jsonObject.toString(), Toast.LENGTH_LONG).show();
Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
} else {
//
//
//This scope runs where the login fails
}
progress.dismiss();
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(LoginActivity.this, "Incorrect username/password, please try again." + t.getMessage(), Toast.LENGTH_LONG).show();
progress.dismiss();
}
});
}
If you are starting this loginactivity using startActivityForResult then handle the response from onActivityResult method in your calling activity.
And
setResult(Activity.RESULT_CANCELED, returnIntent);
this should be
setResult(Activity.RESULT_OK, returnIntent);

Attempt to invoke virtual method on a null object reference? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have code that gets an image by its name from drawables, but for some reason it can't update it.
package com.infonuascape.osrshelper.fragments;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.toolbox.ImageLoader;
import com.infonuascape.osrshelper.R;
import com.infonuascape.osrshelper.activities.MainActivity;
import com.infonuascape.osrshelper.models.Account;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
public class BankViewFragment extends OSRSFragment {
private static final String TAG = "BankViewFragment";
private static Account account;
private ListView lv;
private ImageView iv;
Handler handler;
ArrayList<HashMap<String, String>> ItemList;
public static BankViewFragment newInstance(final Account account) {
BankViewFragment fragment = new BankViewFragment();
Bundle b = new Bundle();
fragment.setArguments(b);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.bank_view, null);
ItemList = new ArrayList<>();
new GetItems().execute();
lv = (ListView) view.findViewById(R.id.list);
handler = new Handler(Looper.getMainLooper());
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String nikas = sharedPref.getString("bankname", "null");
return view;
}
public static int getResId(String resourceName, Class<?> c) {
try {
Field idField = c.getDeclaredField(resourceName);
return idField.getInt(idField);
} catch (Exception e) {
throw new RuntimeException("No resource ID found for: "
+ resourceName + " / " + c, e);
}
}
private class GetItems extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
SharedPreferences sharedpreferences = getContext().getSharedPreferences("minescape", Context.MODE_PRIVATE);
String nikas = sharedpreferences.getString("bankname", "null");
String url = "https://api.minesca.pe/game/classic/stats?username=" + nikas;
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "NIKAS: " + nikas);
Log.e(TAG, "ACCOUNT: " + account);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject items = jsonObj.getJSONObject("bank");
Iterator keys = items.keys();
while(keys.hasNext()) {
String dynamicKey = (String)keys.next();
JSONObject line = items.getJSONObject(dynamicKey);
String item = line.getString("item");
//Integer image = getResId(item, Drawable.class);
final Integer image = getResources().getIdentifier(item, "drawable", getActivity().getPackageName());
String amount = line.getString("amount");
Log.e(TAG, "DAIKTAS: " + item);
Log.e(TAG, "KIEKIS: " + amount);
HashMap<String, String> contact = new HashMap<>();
String itembank = item.replaceAll("i_", "");
String itembanks = itembank.replaceAll("_", " ");
contact.put("name", itembanks);
contact.put("email", amount);
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.bank_view, null);
lv = (ListView) view.findViewById(R.id.list);
// iv = (ImageView) view.findViewById(R.id.logo);
final ImageView ims = (ImageView) lv.findViewById(R.id.logo);
handler.post(new Runnable() {
public void run() {
if(image != null) {
Log.e(TAG, "kas cia jam netinka?: " + image);
if(image == 0) {
ims.setImageResource(R.drawable.i_noted);
Log.e(TAG, "kas cia jam netinka?: " + image);
} else {
Log.e(TAG, "kas cia jam netinka?: " + image);
ims.setImageResource(image);
}
} else {
Log.e(TAG, "null?: " + image);
}
}
});
ItemList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
};
}
} else {
Log.e(TAG, "Couldn't get json from server.");
new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(),
"Couldn't get json from server!",
Toast.LENGTH_LONG).show();
}
};
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(getContext(), ItemList,
R.layout.list_item, new String[]{ "email","name"},
new int[]{R.id.email, R.id.name});
lv.setAdapter(adapter);
}
}
}
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.infonuascape.osrshelper, PID: 31024
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at com.infonuascape.osrshelper.fragments.BankViewFragment$GetItems$1.run(BankViewFragment.java:128)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
The problem is that there's a lot of items, and most of them have the resources, but some don't and i would like to just skip those who don't have, but the main problem is that the app crashes while trying to see the bank.
Yes i have tried to solve my question using similar posts(duplicates), but none of them helped me.
Use this
final ImageView ims = (ImageView) view.findViewById(R.id.logo);
Instead of this
final ImageView ims = (ImageView) lv.findViewById(R.id.logo);

why when i trying to upload image with size 1.5mb it's said error while uploading, but actually the image is successfully upload?

why when i trying to upload image with size 1.5 mb it's said error while uploading, but actually the image is successfully upload? and if i trying to upload with size 100 kb it's said Image Uploaded Successfully
WC_Activity.java
package com.emergency.e_place;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.kosalgeek.android.photoutil.CameraPhoto;
import com.kosalgeek.android.photoutil.GalleryPhoto;
import com.kosalgeek.android.photoutil.ImageBase64;
import com.kosalgeek.android.photoutil.ImageLoader;
import com.kosalgeek.genasync12.AsyncResponse;
import com.kosalgeek.genasync12.EachExceptionsHandler;
import com.kosalgeek.genasync12.PostResponseAsyncTask;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.util.HashMap;
/**
* Created by Eggy on 5/3/2016.
*/
public class WC_Activity extends AppCompatActivity {
final String TAGS = "DEBUG";
String Latitude;
String Longitude;
private final String TAG = this.getClass().getName();
ImageView ivCamera, ivGallery, ivUpload, ivImage;
CameraPhoto cameraPhoto;
GalleryPhoto galleryPhoto;
final int CAMERA_REQUEST = 13323;
final int GALLERY_REQUEST = 22131;
String selectedPhoto;
EditText etIpAddress;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wc);
Toolbar toolbar=(Toolbar)findViewById(R.id.toolbarWC);
setSupportActionBar(toolbar);
//ambil lokasi dari MainActivity
Intent myIntent = getIntent(); // gets the previously created intent
Latitude = myIntent.getStringExtra("Latitude"); // will return "FirstKeyValue"
Longitude= myIntent.getStringExtra("Longitude"); // will return "SecondKeyValue"
Log.d(TAGS, "onLocationChanged: " + Longitude);
etIpAddress = (EditText)findViewById(R.id.etIpAddress);
cameraPhoto = new CameraPhoto(getApplicationContext());
galleryPhoto = new GalleryPhoto(getApplicationContext());
ivImage = (ImageView)findViewById(R.id.ivImage);
ivCamera = (ImageView)findViewById(R.id.ivCamera);
ivGallery = (ImageView)findViewById(R.id.ivGallery);
ivUpload = (ImageView)findViewById(R.id.ivUpload);
ivCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
startActivityForResult(cameraPhoto.takePhotoIntent(), CAMERA_REQUEST);
cameraPhoto.addToGallery();
} catch (IOException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while taking photos", Toast.LENGTH_SHORT).show();
}
}
});
ivGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(galleryPhoto.openGalleryIntent(), GALLERY_REQUEST);
}
});
ivUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(selectedPhoto == null || selectedPhoto.equals("")){
Toast.makeText(getApplicationContext(), "No Image Selected.", Toast.LENGTH_SHORT).show();
return;
}
try {
Bitmap bitmap = ImageLoader.init().from(selectedPhoto).requestSize(1024, 1024).getBitmap();
String encodedImage = ImageBase64.encode(bitmap);
Log.d(TAG, encodedImage);
HashMap<String, String> postData = new HashMap<String, String>();
postData.put("image", encodedImage);
PostResponseAsyncTask task = new PostResponseAsyncTask(WC_Activity.this, postData, new AsyncResponse() {
#Override
public void processFinish(String s) {
Log.d(TAG, s);
if(s.contains("uploaded_success")){
Toast.makeText(getApplicationContext(), "Image Uploaded Successfully.",
Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Error while uploading.",
Toast.LENGTH_SHORT).show();
}
}
});
String ip = etIpAddress.getText().toString();
task.execute("http://" +ip + "/AndroidUpload/upload.php");
task.setEachExceptionsHandler(new EachExceptionsHandler() {
#Override
public void handleIOException(IOException e) {
Toast.makeText(getApplicationContext(), "Cannot Connect to Server.",
Toast.LENGTH_SHORT).show();
}
#Override
public void handleMalformedURLException(MalformedURLException e) {
Toast.makeText(getApplicationContext(), "URL Error.",
Toast.LENGTH_SHORT).show();
}
#Override
public void handleProtocolException(ProtocolException e) {
Toast.makeText(getApplicationContext(), "Protocol Error.",
Toast.LENGTH_SHORT).show();
}
#Override
public void handleUnsupportedEncodingException(UnsupportedEncodingException e) {
Toast.makeText(getApplicationContext(), "Encoding Error.",
Toast.LENGTH_SHORT).show();
}
});
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while encoding photos", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK){
if(requestCode == CAMERA_REQUEST){
String photoPath = cameraPhoto.getPhotoPath();
selectedPhoto = photoPath;
Bitmap bitmap = null;
try {
bitmap = ImageLoader.init().from(photoPath).requestSize(512, 512).getBitmap();
ivImage.setImageBitmap(getRotatedBitmap(bitmap, 90));
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while loading photos", Toast.LENGTH_SHORT).show();
}
}
else if(requestCode == GALLERY_REQUEST){
Uri uri = data.getData();
galleryPhoto.setPhotoUri(uri);
String photoPath = galleryPhoto.getPath();
selectedPhoto = photoPath;
try {
Bitmap bitmap = ImageLoader.init().from(photoPath).requestSize(512, 512).getBitmap();
ivImage.setImageBitmap(bitmap);
} catch (FileNotFoundException e) {
Toast.makeText(getApplicationContext(),
"Something Wrong while choosing photos", Toast.LENGTH_SHORT).show();
}
}
}
}
private Bitmap getRotatedBitmap(Bitmap source, float angle){
Matrix matrix = new Matrix();
matrix.postRotate(angle);
Bitmap bitmap1 = Bitmap.createBitmap(source,
0, 0, source.getWidth(), source.getHeight(), matrix, true);
return bitmap1;
}
}

Android string.equals() doesn't match condition

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"))

Delete an item in listview inside in an arraylist

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();

Categories