Eclipse Android: JSONAdapter not updating ListView - java

I'm following this tutorial: http://www.raywenderlich.com/56111/make-first-android-app-part-3
We are using Async Http with JSONAdapter and attempting to show book data in ListView.
The problem is that when the "Search" button is clicked, nothing happens. The list doesn't even pop up.
Here is my code for MainActivity.java:
package com.example.newapp;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ShareActionProvider;
import android.widget.TextView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
public class MainActivity extends Activity implements View.OnClickListener, OnItemClickListener {
TextView mainTextView;
Button mainButton;
EditText mainEditText;
ListView mainListView;
JSONAdapter mJSONAdapter;
ArrayList mNameList = new ArrayList();
ShareActionProvider mShareActionProvider;
private static final String PREFS = "prefs";
private static final String PREF_NAME = "name";
SharedPreferences mSharedPreferences;
private static final String QUERY_URL = "http://openlibrary.org/search.json?q=";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainEditText = (EditText)findViewById(R.id.main_edittext);
mainTextView = (TextView)findViewById(R.id.main_textview);
mainButton = (Button)findViewById(R.id.main_button);
mainButton.setOnClickListener(this);
mainListView = (ListView)findViewById(R.id.main_listview);
mainListView.setOnItemClickListener(this);
displayWelcome();
// 10. Create a JSONAdapter for the ListView
mJSONAdapter = new JSONAdapter(this, getLayoutInflater());
// Set the ListView to use the ArrayAdapter
mainListView.setAdapter(mJSONAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
MenuItem shareItem = menu.findItem(R.id.menu_item_share);
if (shareItem != null) {
mShareActionProvider = (ShareActionProvider)shareItem.getActionProvider();
}
setShareIntent();
return true;
}
private void setShareIntent() {
if (mShareActionProvider != null) {
// create an Intent with the contents of the TextView
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "Android Development");
shareIntent.putExtra(Intent.EXTRA_TEXT, mainTextView.getText());
// Make sure the provider knows
// it should work with that Intent
mShareActionProvider.setShareIntent(shareIntent);
}
}
#Override
public void onClick(View v) {
queryBooks(mainEditText.getText().toString());
mainEditText.setText("");
}
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
// Log the item's position and contents
// to the console in Debug
}
public void displayWelcome(){
mSharedPreferences = getSharedPreferences(PREFS, MODE_PRIVATE);
String name = mSharedPreferences.getString(PREF_NAME, "");
if (name.length() > 0){
Toast.makeText(this, "Welcome back, " + name + "!", Toast.LENGTH_SHORT).show();
}
else {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Hello!");
alert.setMessage("What is your name?");
final EditText input = new EditText (this);
alert.setView(input);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String inputName = input.getText().toString();
SharedPreferences.Editor e = mSharedPreferences.edit();
e.putString(PREF_NAME, inputName);
e.commit();
Toast.makeText(getApplicationContext(), "Welcome, " + inputName + "!",
Toast.LENGTH_LONG).show();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int whichButton) {
// TODO Auto-generated method stub
}
});
alert.show();
}
}
private void queryBooks(String searchString) {
String urlString = "";
try {
urlString = URLEncoder.encode(searchString, "UTF-8");
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
Toast.makeText(this, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
AsyncHttpClient client = new AsyncHttpClient();
client.get(QUERY_URL + urlString, new JsonHttpResponseHandler(){
public void onSuccess (JSONObject jsonObject) {
//Display a Toast message
//to announce your succcess
Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_LONG).show();
mJSONAdapter.updateData(jsonObject.optJSONArray("docs"));
}
public void onFailure (int statusCode, Throwable throwable, JSONObject error) {
Toast.makeText(getApplicationContext(), "Error: " + statusCode + " " +
throwable.getMessage(), Toast.LENGTH_LONG).show();
Log.e("omg android", statusCode + " " + throwable.getMessage());
}
});
}
}
Here is JSONAdapter.java:
package com.example.newapp;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class JSONAdapter extends BaseAdapter {
private static final String IMAGE_URL_BASE = "http://covers.openlibrary.org/b/id/";
Context mContext;
LayoutInflater mInflater;
JSONArray mJsonArray;
public JSONAdapter (Context context, LayoutInflater inflater) {
mContext = context;
mInflater = inflater;
mJsonArray = new JSONArray();
}
#Override
public int getCount() {
return mJsonArray.length();
}
#Override
public JSONObject getItem(int position) {
return mJsonArray.optJSONObject(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
// check if the view already exists
// if so, no need to inflate and findViewById again!
if (convertView == null) {
// Inflate the custom row layout from your XML.
convertView = mInflater.inflate(R.layout.row_book, null);
// create a new "Holder" with subviews
holder = new ViewHolder();
holder.thumbnailImageView = (ImageView) convertView.findViewById(R.id.img_thumbnail);
holder.titleTextView = (TextView) convertView.findViewById(R.id.text_title);
holder.authorTextView = (TextView) convertView.findViewById(R.id.text_author);
// hang onto this holder for future recyclage
convertView.setTag(holder);
} else {
// skip all the expensive inflation/findViewById
// and just get the holder you already made
holder = (ViewHolder) convertView.getTag();
}
// Get the current book's data in JSON form
JSONObject jsonObject = (JSONObject) getItem(position);
// See if there is a cover ID in the Object
if (jsonObject.has("cover_i")) {
// If so, grab the Cover ID out from the object
String imageID = jsonObject.optString("cover_i");
// Construct the image URL (specific to API)
String imageURL = IMAGE_URL_BASE + imageID + "-S.jpg";
// Use Picasso to load the image
// Temporarily have a placeholder in case it's slow to load
Picasso.with(mContext).load(imageURL).placeholder(R.drawable.ic_books).into(holder.thumbnailImageView);
} else {
// If there is no cover ID in the object, use a placeholder
holder.thumbnailImageView.setImageResource(R.drawable.ic_books);
}
// Grab the title and author from the JSON
String bookTitle = "";
String authorName = "";
if (jsonObject.has("title")) {
bookTitle = jsonObject.optString("title");
}
if (jsonObject.has("author_name")) {
authorName = jsonObject.optJSONArray("author_name").optString(0);
}
// Send these Strings to the TextViews for display
holder.titleTextView.setText(bookTitle);
holder.authorTextView.setText(authorName);
return convertView;
}
private static class ViewHolder {
public ImageView thumbnailImageView;
public TextView titleTextView;
public TextView authorTextView;
}
public void updateData(JSONArray jsonArray) {
// update the adapter's dataset
mJsonArray = jsonArray;
notifyDataSetChanged();
}
}
And here is row_book.xml which is what the list objects should look like:
<?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="75dp">
<ImageView
android:id="#+id/img_thumbnail"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_marginLeft="25dp"
android:layout_centerVertical="true"
android:scaleType="centerInside"/>
<TextView
android:id="#+id/text_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/img_thumbnail"
android:layout_alignTop="#+id/img_thumbnail"
android:layout_marginLeft="25dp"/>
<TextView
android:id="#+id/text_author"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/text_title"
android:layout_alignLeft="#+id/text_title"/>
</RelativeLayout>
Thank you. I hope we can figure out why the list is not updating.

In DetailActivity.Java you need to declare variable like this
TextView myTextView;
Then inside the onCreate method you need to add this
String bookTitle = this.getIntent().getExtras().getString("bookTitle");
Still inside onCreate method you need to check if there is valid bookTitle
if (bookTitle.length() > 0) {
myTextView = (TextView) findViewById(R.id.text_title);
myTextView.setText(String.valueOf(bookTitle));
}
In activity_detail.xml the only thing that was missing on your xml file is
'android:text="#string/textview"' at the top
Change this to look something like below. Have it in mind that you will need to edit layout position to suits your app.
<TextView
android:text="#string/textview"
android:id="#+id/text_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"/>
The book title should now show up. Follow the same procedure to display the author name. I hope this helps.

Related

Referencing TextViews from Activity in Service and Vice versa

I am working on an Android app with a steadily growing Code basis; the aim of the app is to scan and process QR Codes and Barcodes on Handheld Devices for Storages (not Smartphones). It hast two Activities that contain major parts of the programmatical logic; hence, I want to store major parts of the Code that contains the Functionality for processing the Scanner input in an external Service, called Scanner Service, implement the methods there and use the methods in other Activites;
however, I have a major issue with the use of Context, getApplicationContext() and the reference of the Activity in the Service and vice versa; although I think I have referenced and initialised the Textviews from the Activity in the Service, the app keeps on crashing with the following error message:
AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.app.Activity.findViewById(int)' on a null object reference
at com.xxxx.ScanService.<clinit>(ScanService.java:16)
I know what it means, but I donĀ“t know how I could access the View
private static TextView content = (TextView) a.findViewById(R.id.content_detail);
in such a way that I can use it in the Service and in the Activity and the app stops crashing.
Therefore, any hints or help would be very much appreciated, thank you in advance.
The MainDetailActivity:
package com.example.xxx_app;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;
import android.view.MenuItem;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.xxx.ScanService.*;
import static com.xxx.SimpleItemRecyclerViewAdapter.TAGG;
/**
* An activity representing a single Main detail screen. This
* activity is only used on narrow width devices. On tablet-size devices,
* item details are presented side-by-side with a list of items
* in a {#link MainListActivity}.
*/
public class MainDetailActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener,
PopupMenu.OnMenuItemClickListener {
Context context;
private RecyclerView recyclerView;
private RecyclerviewAdapter recyclerviewAdapter;
private RecyclerTouchListener touchListener;
private ListView listView;
public TextView textView4;
public String code;
public static final String TAG = "Barcode ist:" ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_detail);
context = this;
//TextView headerView = findViewById(R.id.txt1);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
EditText editBarcode = (EditText) findViewById(R.id.editText);
TextView content = (TextView) findViewById(R.id.content_detail);
TextView editTextNumber = findViewById(R.id.editTextNumber);
Button addBooking = findViewById(R.id.button);
Button removeBooking = findViewById(R.id.button2);
removeBooking.setEnabled(false);
spinner.setOnItemSelectedListener(this);
//String selectedItem = spinner.getSelectedItem().toString();
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.mockdata, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
String scannedCode = getIntent().getStringExtra("scannedCode");
Log.d(TAG, "scannedCode" + scannedCode);
if (scannedCode != null && (content.getText().toString().equals(""))) {
content.setText(scannedCode);
}
Button btn = findViewById(R.id.imageView4);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(MainDetailActivity.this, v);
popup.setOnMenuItemClickListener(MainDetailActivity.this);
popup.inflate(R.menu.popup_menu);
popup.show();
}
});
editBarcode.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
String code = editBarcode.getText().toString();
if (code.matches("")) //{ if(code.trim().isEmpty())
//|| editBarcode.getText().toString() > 100 )
{
Log.d(TAG, "Code ist leer");
}
if (keyCode == KeyEvent.KEYCODE_ENTER && code.length() > 0) {
editBarcode.setText("");
ScanService.checkEnteredCode(code);
return true;
}
return false;
}
});
recyclerView = findViewById(R.id.recyclerview);
recyclerviewAdapter = new RecyclerviewAdapter(this);
Intent newIntent = getIntent();
String receivedPalNo = newIntent.getStringExtra("palNo");
String receivedNo = newIntent.getStringExtra("no");
String receivedType = newIntent.getStringExtra("type");
String receivedRack = newIntent.getStringExtra("rack");
String receivedCountItems = newIntent.getStringExtra("count_items");
content.setText(receivedCountItems);
RestClient.getPaletteItems(getApplicationContext(),recyclerviewAdapter,receivedPalNo);
Log.d(TAGG,"Intent 1" + receivedPalNo);
Log.d(TAGG, "Intent 2" + receivedNo);
Log.d(TAGG, "Intent 3" + receivedType);
Log.d(TAGG,"Intent 4" + receivedRack);
Log.d(TAGG, "Intent 5" + receivedCountItems);
final ArrayList<Items> itemList = new ArrayList<>();
/*
Items[] items = new Items(12345,123456, 200, 500);
itemList.add(items);*/
recyclerviewAdapter.setItemList((ArrayList<Items>) itemList);
recyclerView.setAdapter(recyclerviewAdapter);
touchListener = new RecyclerTouchListener(this,recyclerView);
RecyclerviewAdapter finalRecyclerviewAdapter = recyclerviewAdapter;
touchListener
.setClickable(new RecyclerTouchListener.OnRowClickListener() {
#Override
public void onRowClicked(int position) {
//Toast.makeText(getApplicationContext(),itemList.get(position), Toast.LENGTH_SHORT).show();
}
#Override
public void onIndependentViewClicked(int independentViewID, int position) {
}
})
.setSwipeOptionViews(R.id.delete_task,R.id.edit_task)
.setSwipeable(R.id.rowFG, R.id.rowBG, new RecyclerTouchListener.OnSwipeOptionsClickListener() {
#Override
public void onSwipeOptionClicked(int viewID, int position) {
switch (viewID){
case R.id.delete_task:
itemList.remove(position);
finalRecyclerviewAdapter.setItemList(itemList);
break;
case R.id.edit_task:
Toast.makeText(getApplicationContext(),"Edit Not Available",Toast.LENGTH_SHORT).show();
break;
}
}
});
recyclerView.addOnItemTouchListener(touchListener);
class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
#Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
}
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don"t need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
String text = getIntent().getStringExtra("palNo");
//headerView.setText(text);
if (receivedType != null && receivedType.equals("FE")) {
ImageView mImgView = findViewById(R.id.id_col_code);
mImgView.setBackgroundResource(R.drawable.backgroun_blue);
}
if (receivedType != null && receivedType.equals("UFE")) {
ImageView mImgView = findViewById(R.id.id_col_code);
mImgView.setBackgroundResource(R.drawable.backgroun_yellow);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(this, "Selected Item: " +item.getTitle(), Toast.LENGTH_SHORT).show();
switch (item.getItemId()) {
case R.id.search_item:
// do your code
return true;
case R.id.upload_item:
// do your code
return true;
case R.id.copy_item:
// do your code
return true;
/* case R.id.print_item:
// do your code
return true;*/
case R.id.share_item:
// do your code
return true;
/*case R.id.bookmark_item:
// do your code
return true;*/
default:
return false;
}
}
public void newDialog(Activity activity) {
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.sortiment_layout);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
Button okButton = dialog.findViewById(R.id.ok);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getApplicationContext(),"Ok" ,Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
Button cancelButton = dialog.findViewById(R.id.cancel);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getApplicationContext(),"Abbrechen" ,Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
dialog.show();
}
public void showDialog(Activity activity) {
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.newcustom_layout);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
Button okButton = dialog.findViewById(R.id.ok);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getApplicationContext(),"Ok" ,Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
dialog.show();
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
navigateUpTo(new Intent(this, MainListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
recyclerView.addOnItemTouchListener(touchListener);
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
The ScanService Class:
package com.example.xxx;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.TextView;
public class ScanService {
private static final String TAG = "Scan Service Tag";
private static Context mContext;
private static Activity a = (MainDetailActivity)mContext;
private static TextView content = (TextView)
a.findViewById(R.id.content_detail);
private static TextView editTextNumber = (TextView)
a.findViewById(R.id.editTextNumber);
public ScanService (Context mContext) {
this.mContext = mContext;
}
public static void checkEnteredCode(String code, Activity a) {
content.setText("");
//PSP-H1-EA-F3
if
(code.matches("PSP-\\p{Upper}\\d\\p{Punct}\\p{Upper}\\" +
"p{Upper}\\p{Punct}\\p{Upper}\\p{Digit}")) {
content.setText("");
content.setText(code);
Log.d(TAG, "xxx");
}
if (code.matches("LF-[0-9]*")) {
///LF-(\d+)/gi
content.setText("");
content.setText(code);
Log.d(TAG, "xxx");
}
if (code.matches("PAL-[0-9][0-9][0-9]")) {
content.setText("");
content.setText(code);
Log.d(TAG, "xxx");
}
if (code.matches("P-[0-9][0-9][0-9]")) {
content.setText("");
content.setText(code);
Log.d(TAG, "Palette");
}
if (code.matches("[0-9][0-9][0-9][0-9].[0-9][0-9].+DB")) {
if(editTextNumber == null) {
Log.d(TAG, "xxx");
}
else {
editTextNumber.setText(code);
Log.d(TAG, "xxx");
}
Log.d(TAG, "xxx");
}
if (code.matches("[0-9A-Z]*[0-9]*")) {
//editBarcode.setText("");
//editBarcode.setText(keyCode);
Log.d(TAG, "xxx");
}
if (code.matches("\\d{13}")) {
//newDialog(MainDetailActivity.this);
//editBarcode.setText("");
//editBarcode.setText(keyCode);
if(editTextNumber == null) {
Log.d(TAG, "xxx");
}
else {
editTextNumber.setText(code);
Log.d(TAG, "xxx");
}
Log.d(TAG, "xxx");
}
else {
Log.d(TAG, "xxx");
};
//editBarcode.setText("");
//editBarcode.setText(code);
/* String code = editBarcode.getText().toString();
if (code.matches("")) //{ if(code.trim().isEmpty())
//|| editBarcode.getText().toString() > 100 )
{
Log.d(TAG, "xxx");
}
//}
checkEnteredCode(code);
//editBarcode.setText("");
return Boolean.parseBoolean(code);*/
Log.d(TAG, code);
}
public static void checkEnteredCode(String code) {
}
}
You cannot access any Views from a Service! Views belong to the Activity. This is the wrong application architecture. A Service performs background processing (file I/O, network I/O, computation, etc.). The Activity is responsible for interacting with the user (inputs, display, etc.). If your Service wants to put data on the screen, you've broken the division of responsibilities. Your Service should simply notify your Activity (or any other component that is interested) when data has changed, and the Activity can then update the View itself. You can share data between the Service and your other components in a number of ways, including: event bus, publish/subscribe, shared preferences, broadcast Intents, SQLite database, etc.

How to use different background color for every listview item

Hello friends I am using a custom listview and this color picker library ' implementation 'petrov.kristiyan:colorpicker-library:1.1.5' here is link library link https://github.com/kristiyanP/colorpicker my problem is that when any user click on any particular item in the listview the color dialog is popped up so user can pick color in this dialog box and change background color of a particular item which successfully I done. But my problem is that how I can save this state for later used here is my picture you get idea what actually i want?
here my picture
here is picture of highlight two item with different color
how can save the state ?
my custom adopter code
package bible.swordof.God;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.opengl.Visibility;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import es.dmoral.toasty.Toasty;
import petrov.kristiyan.colorpicker.ColorPicker;
import static android.content.Context.MODE_PRIVATE;
import static android.database.sqlite.SQLiteDatabase.CONFLICT_NONE;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
import static android.support.constraint.Constraints.TAG;
import static android.support.v4.content.ContextCompat.createDeviceProtectedStorageContext;
import static android.support.v4.content.ContextCompat.startActivity;
public class FullverseAdopter extends ArrayAdapter<String> {
private ALLVERSE activity;
private List<String> versenumber;
private List<String>verseid;
private List<String> verselist;
private List<String> refernce;
TextToSpeech textToSpeech;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private int selectcolor;
ArrayList<String>colors;
public FullverseAdopter(ALLVERSE context, int resource, List<String> versenumber, List<String> verselist, List<String> refernce, List<String>verseid) {
super(context, resource);
this.activity = context;
this.versenumber = versenumber;
this.verselist = verselist;
this.refernce = refernce;
this.verseid=verseid;
}
#Override
public int getCount() {
return versenumber.size();
}
#Override
public String getItem(int position) {
return versenumber.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.versedisplayrow, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
holder.versenumber = (TextView) convertView.findViewById(R.id.versenumber);
holder.verselist = (TextView) convertView.findViewById(R.id.verse);
holder.addfavoruite=(ToggleButton)convertView.findViewById(R.id.adbookmark);
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
holder.versenumber.setText(versenumber.get(position));
holder.verselist.setText(verselist.get(position));
//check if id is exits in db
if(CheckIsDataAlreadyInDBorNot("highlight","verseid",verseid.get(position)))
{
if(verseid.get(position).equals(verseid.get(position))){
}
}
else {
}
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.linearLayout.setBackgroundColor(selectcolor);
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
long delete= mDb.delete("highlight","verseid=?",new String[]{verseid.get(position)});
Toast.makeText(activity, "Remove highlight", Toast.LENGTH_SHORT).show();
}
});
//here color picker dialog popup for chosing color
holder.linearLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("verseid",verseid.get(position));
long check=mDb.insert("highlight",null,contentValues);
//Toasty.success(activity, "PICK COLOR", Toast.LENGTH_SHORT, true).show();
Vibrator vibe = (Vibrator)activity.getSystemService(Context.VIBRATOR_SERVICE);
vibe.vibrate(100);
//id get
Toast.makeText(activity, ""+verseid.get(position), Toast.LENGTH_SHORT).show();
//postion
//Toast.makeText(activity, ""+getItemId(position), Toast.LENGTH_SHORT).show();
ColorPicker colorPicker = new ColorPicker(activity);
colors=new ArrayList<>();
colors.add("#e0e0eb");
colors.add("#ccffff");
colors.add("#ffe6ff");
colors.add("#ffffcc");
colors.add("#ccffcc");
colors.add("#e6f2ff");
colorPicker.setColors(colors).setColumns(4).setTitle("HIGHLIGHT VERSE").setRoundColorButton(true).setOnChooseColorListener(new ColorPicker.OnChooseColorListener() {
#Override
public void onChooseColor(int position, int color) {
holder.linearLayout.setBackgroundColor(color);
}
#Override
public void onCancel() {
}
}).show();
return false;
}
});
/*holder.verselist.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
holder.verselist.setBackgroundColor(Color.parseColor("#e0e0eb"));
return false;
}
});*/
//share verse
holder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toasty.info(activity, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n' + verselist.get(position));
sendIntent.setType("text/plain");
activity.startActivity(sendIntent);
}
});
//add in favourite
holder.addfavoruite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("id",verseid.get(position));
contentValues.put("bookname",refernce.get(position));
contentValues.put("versenumber",versenumber.get(position));
contentValues.put("verse",verselist.get(position));
long check=mDb.insert("favourite",null,contentValues);
Log.d("MY_TAG","DB IS NOW "+check);
Toasty.success(activity, "Added in favouite", Toast.LENGTH_SHORT, true).show();
}else {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});
Toasty.error(activity, "Remove in favouite", Toast.LENGTH_SHORT, true).show();
}
}
});
/* textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
result = textToSpeech.setLanguage(Locale.ENGLISH);
} else {
Toast.makeText(activity, "YOUR DEVICE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
}
}
});
*/
//My toggle button
/* holder.speakverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, "I AM CLICKED", Toast.LENGTH_SHORT).show();
if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) {
Toast.makeText(activity, "Language not supported or Missing", Toast.LENGTH_SHORT).show();
} else {
textToSpeech.speak(verselist.get(position), TextToSpeech.QUEUE_FLUSH, null);
}
}
});*/
return convertView;
}
static class ViewHolder {
private TextView versenumber;
private TextView verselist;
private ImageView share;
private ToggleButton addfavoruite;
private ImageView speakverse;
private LinearLayout linearLayout;
public ViewHolder(View v) {
versenumber = (TextView) v.findViewById(R.id.versenumber);
verselist = (TextView) v.findViewById(R.id.verse);
share = (ImageView) v.findViewById(R.id.share);
/*speakverse = (ImageView) v.findViewById(R.id.speakverse);*/
addfavoruite=(ToggleButton)v.findViewById(R.id.adbookmark);
linearLayout=(LinearLayout)v.findViewById(R.id.layout);
}
}
public boolean CheckIsDataAlreadyInDBorNot(String TableName, String dbfield, String fieldValue) {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getReadableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = mDb.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
// Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
return false;
}else {
// Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();
}
cursor.close();
return true;
}
}
I would suggest to have all your item properties in one object and add the background color to it.
When a color is picked just save it to your verse object and when view is created set it.
Also add the background to your ViewHolder.
public class Verse {
private String versenumber;
private String verseid;
private String verselist;
private String refernce;
private int backgroundColor
// Getters and setters
}
public class FullverseAdopter extends ArrayAdapter<Verse> {
private ALLVERSE activity;
private List<Verse> verse;
TextToSpeech textToSpeech;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private int selectcolor;
ArrayList<String>colors;
public FullverseAdopter(ALLVERSE context, int resource, List<Verse> verse) {
super(context, resource);
this.activity = context;
this.verse = verse;
}
// The rest of your code
}

Android toggle button save state custom listview

Hello friend i am new in android i want to know how to save ToggleButton state in custom ArrayAdapter i create custom ListView with help of ArrayAdapter now i want how save its state in Adapter here is my code pleae explain what logic used to achieve this goal i am on beginner level don't how to achieve this goal?
package bible.swordof.God;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.opengl.Visibility;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import com.hitomi.cmlibrary.CircleMenu;
import com.hitomi.cmlibrary.OnMenuSelectedListener;
import com.hitomi.cmlibrary.OnMenuStatusChangeListener;
import java.util.List;
import java.util.Locale;
import es.dmoral.toasty.Toasty;
import static android.content.Context.MODE_PRIVATE;
import static android.database.sqlite.SQLiteDatabase.CONFLICT_NONE;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
import static android.support.constraint.Constraints.TAG;
import static android.support.v4.content.ContextCompat.createDeviceProtectedStorageContext;
import static android.support.v4.content.ContextCompat.startActivity;
public class FullverseAdopter extends ArrayAdapter < String > {
private ALLVERSE activity;
private List < String > versenumber;
private List < String > verseid;
private List < String > verselist;
private List < String > refernce;
TextToSpeech textToSpeech;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private boolean save;
public static final String MyPREFERENCES = "MyPrefs";
//check for availabe language
int result;
public FullverseAdopter(ALLVERSE context, int resource, List < String > versenumber, List < String > verselist, List < String > refernce, List < String > verseid) {
super(context, resource, versenumber);
this.activity = context;
this.versenumber = versenumber;
this.verselist = verselist;
this.refernce = refernce;
this.verseid = verseid;
}
#Override
public int getCount() {
return versenumber.size();
}
#Override
public String getItem(int position) {
return versenumber.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.versedisplayrow, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
holder.versenumber = (TextView) convertView.findViewById(R.id.versenumber);
holder.verselist = (TextView) convertView.findViewById(R.id.verse);
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
holder.versenumber.setText(versenumber.get(position));
holder.verselist.setText(verselist.get(position));
//share verse
holder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toasty.info(activity, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n' + verselist.get(position));
sendIntent.setType("text/plain");
activity.startActivity(sendIntent);
}
});
textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
result = textToSpeech.setLanguage(Locale.ENGLISH);
} else {
Toast.makeText(activity, "YOUR DEVICE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
}
}
});
//My toggle button
holder.bookmark.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
} else {
}
}
});
//mDBHelper = new DatabaseHelper(activity);
//mDb = mDBHelper.getWritableDatabase();
//ContentValues contentValues=new ContentValues();
//contentValues.put("id",verseid.get(position));
//contentValues.put("bookname",refernce.get(position));
//contentValues.put("versenumber",versenumber.get(position));
//contentValues.put("verse",verselist.get(position));
//long check=mDb.insert("favourite",null,contentValues);
//Log.d("MY_TAG","DB IS NOW "+check);
//Toasty.success(activity, "Added in favouite"+check, Toast.LENGTH_SHORT, true).show();
holder.speakverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, "I AM CLICKED", Toast.LENGTH_SHORT).show();
if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) {
Toast.makeText(activity, "Language not supported or Missing", Toast.LENGTH_SHORT).show();
} else {
textToSpeech.speak(verselist.get(position), TextToSpeech.QUEUE_FLUSH, null);
}
}
});
/* holder.removebookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
// long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});
//Toasty.error(activity, "Remove in favouite"+delete, Toast.LENGTH_SHORT, true).show();
}
});*/
return convertView;
}
static class ViewHolder {
private ToggleButton favourite;
private TextView versenumber;
private TextView verselist;
private CircleMenu circleMenu;
private ImageView share;
//toggle button
public ToggleButton bookmark;
private boolean defaultvalue;
private ALLVERSE activity;
private ImageView speakverse;
public ViewHolder(View v) {
versenumber = (TextView) v.findViewById(R.id.versenumber);
verselist = (TextView) v.findViewById(R.id.verse);
share = (ImageView) v.findViewById(R.id.share);
bookmark = (ToggleButton) v.findViewById(R.id.adbookmark);
speakverse = (ImageView) v.findViewById(R.id.speakverse);
}
}
}
Ideally an adapter is an object to adapt a particular dataset to render a view within a listview. So you should have a data structure (class object) for every row visible in that list view and put it in an array list. Based on the position in getView method, retrieve the data for the row and initialize views from this data. Now this data set can be saved on server or in local memory in any format preferably in JSON and can be retrieved back in future.

Recyclerview button on specific row - how to capture row id before onclicklistener?

Below is my adapter class and view code, where I am showing 2 buttons for each of the row. I have setup 2 diff listeners for each button.
New to android, I am not sure, how to get the getbarCode() (sort of row id) for the specific row button clicked? (This I want to use to set the barcode b4 I call my webservices). Currently I have hardcoded in code, I want to get it from my Books getbarCode().
Any suggestions?
BookListMyAdapter.java
package com.androidatc.customviewindrawer;
import android.app.Activity;
import android.app.ProgressDialog;
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.ProgressBar;
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.RequestHandle;
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;
final ProgressDialog progress;
// 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);
renewBtn.setOnClickListener(this); // <- This lines
returnBtn.setOnClickListener(this); // <- This lines
progress = new ProgressDialog(myActivity);
}
#Override
public void onClick(View itemView) {
switch (itemView.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, progress);
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, progress);
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 ProgressDialog progress) {
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", "B1246857");
//B1246857
//B1246855
params.put("patron", "thida");
// Toast.makeText(myActivity.getApplicationContext(), "B4 calling webservice", Toast.LENGTH_LONG).show();
client.post(" http:tron_id=2&item=1", new TextHttpResponseHandler() {
#Override
public void onSuccess(int i, Header[] headers, String response) {
Toast.makeText(myActivity.getApplicationContext(), "Response renew: " + response, Toast.LENGTH_LONG).show();
Log.d("TAG", "Success");
progress.dismiss();
}
#Override
public void onFailure(int statusCode, Header[] headers, String response, Throwable error) {
Toast.makeText(myActivity.getApplicationContext(), "Status code :" + statusCode + "errmsg : " + error.getMessage(), Toast.LENGTH_LONG).show();
// Toast.makeText(myActivity.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");
progress.dismiss();
}
}
);
} catch (Exception e) {
e.printStackTrace();
//illegal argument exception
Toast.makeText(myActivity.getApplicationContext(), "Exception Caught" + e.toString(), Toast.LENGTH_LONG).show();
}
// progress.dismiss();
// Toast.makeText(myActivity.getApplicationContext(), "After calling webservice renew", 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>
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, String [] barCode){
books = new ArrayList<>();
for(int i = 0;i<total;i++)
{
books.add(new Books(titles[i], dueDts[i], barCode[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);
}
Books.java
package com.androidatc.customviewindrawer;
class Books {
String title;
String dueOn;
public String getBarCode() {
return barCode;
}
public void setBarCode(String barCode) {
this.barCode = barCode;
}
// int photoId;
String barCode;
Books(String title, String dueOn, String barCode) {
this.title = title;
this.dueOn = dueOn;
this.barCode = barCode;
// this.photoId = photoId;
}
}
You need getAdapterPosition() (https://developer.android.com/reference/android/support/v7/widget/RecyclerView.ViewHolder.html#getAdapterPosition())
And then get the access (or path the event) List<Books> books; in your adapter.
The easiest way (if you do not need your ViewHolder as static class) is making it just public class and so you will get access as the inner class of the adapter.

I have two activity.When i was click on first activity list view,second activity open. number of count in first activity also increase

I have two activities. When I clicked on first activity in list view, second activity opened .Second activity have one button number of item. when I clicked on second activity number of count goes to first activity. It is repeated process but number of count in first activity also gets increased.
My first activity..
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView;
import android.os.Bundle;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.adapter.ListAdapterAddItems;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.json.JSONfunctions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.ArrayList;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class DetaisRESTActivity extends Activity {
String messagevaluename,totalamount,valueid,valueid1,valuename,pos;
public String countString=null;
public int count=0;
public String message=null;
public static String message1=null;
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ArrayList aa;
public TextView mTitleTextView;
public ImageButton imageButton;
ListAdapterAddItems adapter;
public TextView restaurantname = null;
public TextView ruppees = null;
String restaurantmenuname,rastaurantname;
ProgressDialog mProgressDialog;
ArrayList<ListModel> arraylist;
public static String RASTAURANTNAMEDETAILS = "RestaurantPizzaItemName";
public static String RASTAURANTRUPPEES = "RestaurantPizzaItemPrice";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_detais_rest);
// getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.titlebar);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
LayoutInflater mInflater = LayoutInflater.from(this);
View mCustomView = mInflater.inflate(R.layout.titlebar, null);
mTitleTextView = (TextView) mCustomView.findViewById(R.id.textView123456789);
imageButton = (ImageButton) mCustomView
.findViewById(R.id.imageButton2);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Refresh Clicked!",
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
startActivity(i);
}
});
actionBar.setCustomView(mCustomView);
actionBar.setDisplayShowCustomEnabled(true);
Intent intent = getIntent();
// get the extra value
valuename = intent.getStringExtra("restaurantmenuname");
valueid = intent.getStringExtra("restaurantmenunameid");
valueid1 = intent.getStringExtra("idsrestaurantMenuId5");
//totalamount = intent.getStringExtra("ruppees");
Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
// Log.i("totalamount",totalamount);
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void,Void,Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(DetaisRESTActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
Toast.makeText(DetaisRESTActivity.this, "Successs", Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<ListModel>();
// Retrieve JSON Objects from the given URL address
// Log.i("123",value1);
jsonobject = JSONfunctions.getJSONfromURL("http://firstchoicefood.in/fcfapiphpexpert/phpexpert_restaurantMenuItem.php?r=" + URLEncoder.encode(valuename) + "&resid=" + URLEncoder.encode(valueid1) + "&RestaurantCategoryID=" + URLEncoder.encode(valueid) + "");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("RestaurantMenItems");
Log.i("1234",""+jsonarray);
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
ListModel sched = new ListModel();
sched.setId(jsonobject.getString("id"));
sched.setProductName(jsonobject.getString("RestaurantPizzaItemName"));
sched.setPrice(jsonobject.getString("RestaurantPizzaItemPrice"));
arraylist.add(sched);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listViewdetails);
adapter = new ListAdapterAddItems();
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
//listview.invalidateViews();
adapter.notifyDataSetChanged();
// listview.notifyAll();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
{
// Get Person "behind" the clicked item
ListModel p =(ListModel)listview.getItemAtPosition(position);
// Log the fields to check if we got the info we want
Log.i("SomeTag",""+p.getId());
//String itemvalue=(String)listview.getItemAtPosition(position);
Log.i("SomeTag", "Persons name: " + p.getProductName());
Log.i("SomeTag", "Ruppees: " + p.getPrice());
//count++;
//countString=String.valueOf(count);
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
//Toast.makeText(getBaseContext(),
// countString, Toast.LENGTH_LONG).show();
Log.i("postititi",""+position);
// mTitleTextView.setText(countString);
Intent intent=new Intent(DetaisRESTActivity.this,QuentityActivity.class);
intent.putExtra("quentity",countString);
intent.putExtra("valueid",valueid);
intent.putExtra("valuename",valuename);
intent.putExtra("valueid1",valueid1);
intent.putExtra("id",p.getId());
intent.putExtra("name",p.getProductName());
intent.putExtra("price",p.getPrice());
startActivityForResult(intent,2);
// startActivity(intent);
}
});
}
}
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 2
if(requestCode==2)
{
// aa=new ArrayList();
pos=data.getStringExtra("POSITION");
message=data.getStringExtra("MESSAGE");
message1=data.getStringExtra("COUNTSTRING");
messagevaluename=data.getStringExtra("VALUENAME");
Log.i("xxxxxxxxxxx",message);
Log.i("xxxxxxxxxxx1234",pos);
Log.i("xxxxxxxxxxx5678count",message1);
Log.i("messagevaluename",messagevaluename);
//ruppees.setText(message);
mTitleTextView.setText(message1);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_LONG).show();
Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
i.putExtra("ruppees",message);
i.putExtra("id",pos);
i.putExtra("messagevaluename",messagevaluename);
startActivity(i);
}
});
}
}
//==========================
class ListAdapterAddItems extends ArrayAdapter<ListModel>
{
ListAdapterAddItems(){
super(DetaisRESTActivity.this,android.R.layout.simple_list_item_1,arraylist);
//imageLoader = new ImageLoader(MainActivity.this);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(R.layout.cartlistitem, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.populateFrom(arraylist.get(position));
// arraylist.get(position).getPrice();
return convertView;
}
}
class ViewHolder {
ViewHolder(View row) {
restaurantname = (TextView) row.findViewById(R.id.rastaurantnamedetailsrestaurant);
ruppees = (TextView) row.findViewById(R.id.rastaurantcuisinedetalsrestaurant);
}
// Notice we have to change our populateFrom() to take an argument of type "Person"
void populateFrom(ListModel r) {
restaurantname.setText(r.getProductName());
ruppees.setText(r.getPrice());
}
}
//=============================================================
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_detais_rest, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return super.onOptionsItemSelected(item);
}
}
Second activity....
package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.json.JSONfunctions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.ArrayList;
public class QuentityActivity extends Activity {
String value=null;
public String TotAmt=null;
String Name;
ImageButton positive,negative;
String position;
int count = 1;
int tot_amt = 0;
public String countString=null;
String Rs,name,price;
String valueid,valueid1,valuename;
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
public TextView ruppees,submenuname,totalruppees,quantity,addtocart;
ProgressDialog mProgressDialog;
ArrayList<ListModel> arraylist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quentity);
ActionBar actionBar = getActionBar();
// Enabling Up / Back navigation
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
Intent intent = getIntent();
// get the extra value
value = intent.getStringExtra("quentity");
valuename = intent.getStringExtra("valuename");
valueid = intent.getStringExtra("valueid");
valueid1 = intent.getStringExtra("valueid1");
name=intent.getStringExtra("name");
price=intent.getStringExtra("price");
position=intent.getStringExtra("id");
Log.i("valueid",valueid);
Log.i("valuename",valuename);
Log.i("valueid1",valueid1);
Log.i("name",name);
Log.i("price",price);
Log.i("id1",position);
quantity=(TextView)findViewById(R.id.rastaurantcuisinedetalsrestaurantquantity);
totalruppees=(TextView)findViewById(R.id.rastaurantnamequentitytotal1);
submenuname=(TextView)findViewById(R.id.rastaurantnamesubmenuquentity);
ruppees=(TextView)findViewById(R.id.rastaurantnamequentity1);
positive=(ImageButton)findViewById(R.id.imageButtonpositive);
negative=(ImageButton)findViewById(R.id.imageButtonnegative);
addtocart=(TextView)findViewById(R.id.textViewaddtocart);
buttonclick();
addtocart();
// value1 = intent.getStringExtra("numericitem");
// int numericvalue = intent.getIntExtra("numericitem", 11);
submenuname.setText(name);
ruppees.setText(price);
totalruppees.setText(price);
// new DownloadJSON().execute();
}
public void buttonclick(){
positive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getString =quantity.getText().toString();
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
//count = Integer.parseInt(getString);
count++;
countString = String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
negative.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getString =quantity.getText().toString();
String totalAmtString = ruppees.getText().toString();
int totAmount = Integer.parseInt(totalAmtString);
//count = Integer.parseInt(getString);
if (count > 1)
count--;
countString = String.valueOf(count);
tot_amt = totAmount * count;
TotAmt = String.valueOf(tot_amt);
totalruppees.setText(TotAmt);
quantity.setText(countString);
}
});
}
public void addtocart(){
addtocart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=new Intent();
intent.putExtra("MESSAGE",TotAmt);
intent.putExtra("POSITION",position);
intent.putExtra("COUNTSTRING",countString);
intent.putExtra("VALUENAME",valuename);
setResult(2,intent);
finish();//finishing activity
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_quentity, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Categories