Hi guys I am looking for a bit of help and advise with my app, At the moment I have a custom adapter printing out each row, in each row it prints two buttons, one button to increment and one button to decrement. What I want to happen is for when a button is clicked a editText(totalCost) outside the listView changes. I have no idea how to go about doing this as I am pretty new to android and java, so any help will be great. Thanks
The custom adapter that I am using is
package com.example.rory.dbtest;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.pinchtapzoom.R;
public class CustomCursorAdapter extends CursorAdapter{
public int counter = 0;
public CustomCursorAdapter(Context context, Cursor c) {
super(context, c);
this.context = context;
}
Context context;
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.row, parent, false);
return retView;
}
public void bindView(View view, Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
TextView textViewPersonName = (TextView) view.findViewById(R.id.item1);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
final EditText edit1 = (EditText) view.findViewById(R.id.runningTotal);
Button plusButton = (Button) view.findViewById(R.id.plusButton);
plusButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
counter++;
edit1.setText(Integer.toString(counter));
}
});
Button minusButton = (Button) view.findViewById(R.id.minusButton);
minusButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
counter--;
edit1.setText(Integer.toString(counter));
}
});
}
}
This is the main activity where I want the editText(TotalCost) to change depending on the click
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.pinchtapzoom.R;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.SQLException;
public class MyActivity extends Activity {
private CustomCursorAdapter customAdapter;
public ListView list1;
com.example.rory.dbtest.DBAdapter db = new com.example.rory.dbtest.DBAdapter(this);
public EditText TotalCost;
//public EditText TotalLitres;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
list1 = (ListView)findViewById(R.id.data_list);
db.open();
Button addBtn = (Button)findViewById(R.id.add);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, addassignment.class);
startActivity(i);
}
});
Button deleteBtn = (Button)findViewById(R.id.delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Delete.class);
startActivity(i);
}
});
Button updateBtn = (Button)findViewById(R.id.update);
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Update.class);
startActivity(i);
}
});
try {
String destPath = "/data/data/" + getPackageName() + "/databases/AssignmentDB";
File f = new File(destPath);
if (!f.exists()) {
CopyDB( getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
new Handler().post(new Runnable() {
#Override
public void run() {
//Log.d("test", "customadapter is " + customAdapter.toString());
//Log.d("test", "databaseHelper is " + databaseHelper.toString());
customAdapter = new CustomCursorAdapter(MyActivity.this, db.getAllRecords());
list1.setAdapter(customAdapter);
}
});
}
private class DBAdapter extends BaseAdapter {
private LayoutInflater mInflater;
//private ArrayList<>
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
return null;
}
}
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
//---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
}
And the XML file for the adapter
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView android:id="#+id/item1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="item"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textSize="30sp"
android:paddingBottom="5dp"/>
<Button
android:id="#+id/plusButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/plusButton"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<EditText
android:id="#+id/runningTotal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/minusButton"
android:layout_toStartOf="#+id/minusButton"
android:layout_marginRight="30dp" />
<Button
android:id="#+id/minusButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/minusButton"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
You should use an Interface
1) create an interface class:
public interface MyAdapterInterface {
public void updateEditText(String value);
}
2) change your adapter to:
public class CustomCursorAdapter extends CursorAdapter{
public int counter = 0;
private MyAdapterInterface mMyInterface;
public CustomCursorAdapter(Context context, Cursor c, MyAdapterInterface myInterface) {
super(context, c);
this.context = context;
this.mMyInterface = myInterface;
}
Context context;
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.row, parent, false);
return retView;
}
public void bindView(View view, Context context, Cursor cursor) {
// here we are setting our data
// that means, take the data from the cursor and put it in views
TextView textViewPersonName = (TextView) view.findViewById(R.id.item1);
textViewPersonName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
final EditText edit1 = (EditText) view.findViewById(R.id.runningTotal);
Button plusButton = (Button) view.findViewById(R.id.plusButton);
plusButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
counter++;
edit1.setText(Integer.toString(counter));
mMyInterface.updateEditText(/*YOUR VALUE*/);
}
});
Button minusButton = (Button) view.findViewById(R.id.minusButton);
minusButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
counter--;
edit1.setText(Integer.toString(counter));
mMyInterface.updateEditText(/*YOUR VALUE*/);
}
});
}
}
3) implement the interface in your activity:
public class MyActivity extends Activity implements MyAdapterInterface {
private CustomCursorAdapter customAdapter;
public ListView list1;
com.example.rory.dbtest.DBAdapter db = new com.example.rory.dbtest.DBAdapter(this);
public EditText TotalCost;
//public EditText TotalLitres;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
list1 = (ListView)findViewById(R.id.data_list);
db.open();
Button addBtn = (Button)findViewById(R.id.add);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, addassignment.class);
startActivity(i);
}
});
Button deleteBtn = (Button)findViewById(R.id.delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Delete.class);
startActivity(i);
}
});
Button updateBtn = (Button)findViewById(R.id.update);
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Update.class);
startActivity(i);
}
});
try {
String destPath = "/data/data/" + getPackageName() + "/databases/AssignmentDB";
File f = new File(destPath);
if (!f.exists()) {
CopyDB( getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
new Handler().post(new Runnable() {
#Override
public void run() {
//Log.d("test", "customadapter is " + customAdapter.toString());
//Log.d("test", "databaseHelper is " + databaseHelper.toString());
customAdapter = new CustomCursorAdapter(MyActivity.this, db.getAllRecords(), this);
list1.setAdapter(customAdapter);
}
});
#Override
public void updateEditText(String value) {
EditText myEditText = (EditText)findViewById(R.id./*YOUR EDITTEXT ID*/);
myEditText.setText(value);
}
}
private class DBAdapter extends BaseAdapter {
private LayoutInflater mInflater;
//private ArrayList<>
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
return null;
}
}
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
//---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
}
Related
I created a ListView and a custom adapter to use with the list view. For some reason, if I add more than one item to the list, it does show several items, but all of them are identical to the first one.
At first I used a layout file to create each item but then I gave up and dynamically created a text view just to test it. It didn't work in both ways.
List with same item
Here is my code:
ArtistAdapter.java
package com.example.list2;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class ArtistAdapter extends BaseAdapter
{
private ArrayList<String> artists;
private Context context;
private LayoutInflater inflater;
public ArtistAdapter(Context context, ArrayList<String> artists)
{
super();
this.context = context;
this.artists = artists;
this.inflater = LayoutInflater.from(context);
}
public ArtistAdapter(Context context)
{
this(context, new ArrayList<String>());
}
#Override
public int getCount() {
return artists.size();
}
#Override
public String getItem(int i) {
return artists.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
if(v == null)
{
//LayoutInflater li = ((Activity)context).getLayoutInflater();
//v = inflater.inflate(R.layout.item,viewGroup,false);
//((TextView)v.findViewById(R.id.name)).setText((String)getItem(i));
v = new TextView(context);
((TextView)v).setText(getItem(i));
((TextView)v).setTextSize(50);
}
return v;
}
public void add(String name)
{
artists.add(name);
notifyDataSetChanged();
}
}
MainActivity.java
package com.example.list2;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.lang.reflect.Array;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ListView l;
EditText et;
Button bt;
//ArrayAdapter<String> aa;
ArtistAdapter aa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l = findViewById(R.id.list);
et = findViewById(R.id.input);
bt = findViewById(R.id.submit);
bt.setOnClickListener(this);
//aa = new ArrayAdapter<String>(this,R.layout.item,new ArrayList<String>());
aa = new ArtistAdapter(this);
l.setAdapter(aa);
}
#Override
public void onClick(View v) {
String inp = getInput();
if(inp.length() == 0) return;
aa.add(inp);
//aa.notifyDataSetChanged();
empty();
}
private String getInput()
{
return et.getText().toString();
}
private void empty()
{
et.setText("");
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"
>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/input"
android:hint="Something..."
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/submit"
android:text="Submit!"
/>
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/list"
android:animateLayoutChanges="true"
></ListView>
</LinearLayout>
Do you need to use a custom Adapter? Otherwise this code works well using ArrayAdapter:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ListView l;
EditText et;
Button bt;
ArrayAdapter<String> artistAdapter;
List<String> listItems = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l = findViewById(R.id.list);
et = findViewById(R.id.input);
bt = findViewById(R.id.submit);
bt.setOnClickListener(this);
artistAdapter = new ArrayAdapter<String>(this,R.layout.item, R.id.textView,listItems);
l.setAdapter(artistAdapter);
}
#Override
public void onClick(View v) {
String inp = getInput();
if(inp.length() == 0) return;
listItems.add(inp);
artistAdapter.notifyDataSetChanged();
empty();
}
private String getInput()
{
return et.getText().toString();
}
private void empty()
{
et.setText("");
}
}
You need to update the arraylist and then set the adapter. For some reason notify adapter is not working. Here's the solution:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
ListView l;
EditText et;
Button bt;
ArtistAdapter artistAdapter;
ArrayList<String> arrayList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
l = findViewById(R.id.list);
et = findViewById(R.id.input);
bt = findViewById(R.id.submit);
bt.setOnClickListener(this);
artistAdapter = new ArtistAdapter(this, arrayList);
l.setAdapter(artistAdapter);
}
#Override
public void onClick(View v) {
String inp = getInput();
if(inp.length() == 0) return;
arrayList.add(inp);
l.setAdapter(artistAdapter);
empty();
}
private String getInput()
{
return et.getText().toString();
}
private void empty()
{
et.setText("");
}
}
====
public class ArtistAdapter extends BaseAdapter
{
private ArrayList artists;
private Context context;
public ArtistAdapter(Context context, ArrayList<String> artists)
{
super();
this.context = context;
this.artists = artists;
}
#Override
public int getCount() {
return artists.size();
}
#Override
public String getItem(int i) {
return artists.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
if(v == null)
{
v = new TextView(context);
((TextView)v).setText(getItem(i));
((TextView)v).setTextSize(50);
}
return v;
}
}
I am working on a shopping Android app, I have a CartActivity. In my CartActivity I put RecyclerView and each row in this RecyclerView have 2 buttons, one (+) button to increase the quantity for this item in the cart and other (-) button to delete 1 from the quantity of this item in the row.
Now when I have a single item in my cart, everything is ok. but when I have multi-item in cart (multi-row in RV) I have the issue which is: When I press (+) or (-) button on any item in RecyclerView the effect of quantity changing shown on the last item in this list (last row) and there is no changing on my selected row!
this is my adapter code:
package com.example.souqsenae.adapters;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;
import com.example.souqsenae.API_Utility.IApi;
import com.example.souqsenae.API_Utility.RetrofitBuilder;
import com.example.souqsenae.R;
import com.example.souqsenae.activities.cartActivity;
import com.example.souqsenae.models.AddToCart;
import com.example.souqsenae.models.CartInfo;
import com.example.souqsenae.models.Parts;
import com.example.souqsenae.models.RemoveProduct;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class CartAdapter extends
RecyclerView.Adapter<CartAdapter.CartAdapterViewHolder> {
private Context context;
private ArrayList<CartInfo.Item> mItem;
private ItemOnClickHandler mItemOnClickHandler;
RetrofitBuilder rB = new RetrofitBuilder();
IApi service = rB.retrofit.create(IApi.class);
int totalQty =0; int subTotal = 0;
TextView tv1, tv4;
private static SharedPreferences pref;
String cookie;
public CartAdapter(ItemOnClickHandler cartAdapterOnClickHandler, Context _context) {
mItemOnClickHandler = cartAdapterOnClickHandler;
pref = _context.getSharedPreferences("log", Context.MODE_PRIVATE);
}
public void setProductsData(ArrayList<CartInfo.Item> item) {
mItem = item;
notifyDataSetChanged();
}
public void addAll(ArrayList<CartInfo.Item> newList) {
int lastIndex = getItemCount();
mItem.addAll(newList);
notifyItemRangeInserted(lastIndex, newList.size());
}
public void clear() {
int size = mItem.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
mItem.remove(0);
}
notifyItemRangeRemoved(0, size);
}
}
#Override
public CartAdapter.CartAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View contactView = inflater.inflate(R.layout.row_cart, parent, false);
// Return a new holder instance
CartAdapterViewHolder viewHolder = new CartAdapterViewHolder(contactView);
return viewHolder;
}
#Override
public void onBindViewHolder(CartAdapter.CartAdapterViewHolder viewHolder, int position) {
// viewHolder.iv.setAnimation(AnimationUtils.loadAnimation(context, R.anim.fade_transition_animation));
viewHolder.container.setAnimation(AnimationUtils.loadAnimation(context,R.anim.fade_transition_animation));
final CartInfo.Item cartInfo = mItem.get(position);
tv1 = viewHolder.qty;
TextView tv2 = viewHolder.tvItemName;
TextView tv3 = viewHolder.tvItemDesc;
tv4 = viewHolder.tvSubTotal;
Button button = viewHolder.btnMin;
Button button1 = viewHolder.btnPlus;
totalQty = cartInfo.getQty();
tv1.setText(String.valueOf(totalQty));
tv2.setText(cartInfo.getName());
tv4.setText(String.valueOf(cartInfo.getSubtotal()));
cookie = pref.getString("cookie", "");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if((totalQty -1) >0){
totalQty = totalQty -1;
tv1.setText(String.valueOf(totalQty));
subTotal = totalQty * (cartInfo.getPrice());
tv4.setText(String.valueOf(subTotal));
}
if((totalQty - 1) == 0){
// remove from cart:
String row = cartInfo.getRowid();
String product_id = cartInfo.getId();
Call<RemoveProduct> call = service.updateCartQty( cookie,product_id,totalQty);
call.enqueue(new Callback<RemoveProduct>() {
#Override
public void onResponse(Call<RemoveProduct> call, Response<RemoveProduct> response) {
if(response.isSuccessful()){
notifyDataSetChanged();
Intent intent = new Intent(context, cartActivity.class);
context.startActivity(intent);
}
}
#Override
public void onFailure(Call<RemoveProduct> call, Throwable t) {
}
});
}
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int vendor = Integer.parseInt(cartInfo.getVendor());
int product_id = Integer.parseInt(cartInfo.getId());
Call<AddToCart> call = service.addToCart(cookie,product_id,vendor,1);
call.enqueue(new Callback<AddToCart>() {
#Override
public void onResponse(Call<AddToCart> call, Response<AddToCart> response) {
if(response.isSuccessful()){
totalQty = totalQty +1;
tv1.setText(String.valueOf(totalQty));
subTotal = totalQty * (cartInfo.getPrice());
tv4.setText(String.valueOf(subTotal));
}
}
#Override
public void onFailure(Call<AddToCart> call, Throwable t) {
}
});
}
});
}
// Returns the total count of items in the list
#Override
public int getItemCount() {
if(mItem == null) {
return 0;
}
return mItem.size();
}
public class CartAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public final Button btnPlus;
public final Button btnMin;
public final TextView qty;
public final TextView tvItemName;
public final TextView tvItemDesc;
public final TextView tvSubTotal;
public final LinearLayout container;
public CartAdapterViewHolder(View view) {
super(view);
qty = (TextView) view.findViewById(R.id.partCount);
tvItemName = (TextView) view.findViewById(R.id.tv_item_name);
tvItemDesc = (TextView) view.findViewById(R.id.tv_item_description);
tvSubTotal = (TextView) view.findViewById(R.id.tvSubTotal);
btnMin = (Button) view.findViewById(R.id.btnMin);
btnPlus = (Button) view.findViewById(R.id.btnPlus);
container = (LinearLayout) view.findViewById(R.id.layout_part_item);
view.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int position = getAdapterPosition();
CartInfo.Item selectedProduct = mItem.get(position);
mItemOnClickHandler.onClickItem(selectedProduct);
}
}
public interface ItemOnClickHandler {
void onClickItem(CartInfo.Item cartInfo);
}
}
I don't know what the wrong :(
Thanks
Better to use interface to perform click operations.
Whenever button clicked, update the quantity for a specific item and call adapter.notifyDataSetChanged();.
You have to made change for quantity in your model when click + or - button. So you have to add cartInfo.setQty(totalQty); inside your button clicks
Don't use global variables if you are using variable inside onBind()
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if((totalQty -1) >0){
cartInfo.setQty(cartInfo.getQty() -1);
tv1.setText(String.valueOf(cartInfo.getQty()));
tv4.setText(String.valueOf(cartInfo.getQty() * (cartInfo.getPrice())));
}
if((totalQty - 1) == 0){
// remove from cart:
String row = cartInfo.getRowid();
String product_id = cartInfo.getId();
mItem.remove(cartInfo);
Call<RemoveProduct> call = service.updateCartQty( cookie,product_id,totalQty);
call.enqueue(new Callback<RemoveProduct>() {
#Override
public void onResponse(Call<RemoveProduct> call, Response<RemoveProduct> response) {
if(response.isSuccessful()){
notifyDataSetChanged();
Intent intent = new Intent(context, cartActivity.class);
context.startActivity(intent);
}
}
#Override
public void onFailure(Call<RemoveProduct> call, Throwable t) {
}
});
notifyDataSetChanged();
}
}
});
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int vendor = Integer.parseInt(cartInfo.getVendor());
int product_id = Integer.parseInt(cartInfo.getId());
cartInfo.setQty(cartInfo.getQty()+1);
cartInfo.setQty(cartInfo.getQty()+1);
tv1.setText(String.valueOf(cartInfo.getQty()));
tv4.setText(String.valueOf(cartInfo.getQty() * (cartInfo.getPrice())));
Call<AddToCart> call = service.addToCart(cookie,product_id,vendor,1);
call.enqueue(new Callback<AddToCart>() {
#Override
public void onResponse(Call<AddToCart> call, Response<AddToCart> response) {
if(response.isSuccessful()){
}
}
#Override
public void onFailure(Call<AddToCart> call, Throwable t) {
}
});
}
});
I want to implement session for intro slide which when after installing the app for the first time I want to appear it and for the second time kill it.. but I don't know implement it because it doesn't have layout.. and not working
IntroActivity.java
package com.gnex_tech.bugisberdagang;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import agency.tango.materialintroscreen.MaterialIntroActivity;
import agency.tango.materialintroscreen.SlideFragmentBuilder;
public class IntroActivity extends MaterialIntroActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setSkipButtonVisible();
enableLastSlideAlphaExitTransition(true);
addSlide(new SlideFragmentBuilder()
.backgroundColor(R.color.bg_screen1)
.buttonsColor(R.color.btn_screen1)
.image(R.drawable.welcome_slider_1)
.title(getString(R.string.intro_title1))
.description(getString(R.string.intro_desc_title1))
.build());
addSlide(new SlideFragmentBuilder()
.backgroundColor(R.color.bg_screen2)
.buttonsColor(R.color.btn_screen2)
.image(R.drawable.welcome_slider_2)
.title(getString(R.string.intro_title2))
.description(getString(R.string.intro_desc_title2))
.build());
addSlide(new SlideFragmentBuilder()
.backgroundColor(R.color.bg_screen3)
.buttonsColor(R.color.btn_screen3)
.image(R.drawable.welcome_slider_3)
.title(getString(R.string.intro_title3))
.description(getString(R.string.intro_desc_title3))
.build());
}
#Override
public void onFinish() {
Intent intent = new Intent(IntroActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
and Session.java
package com.gnex_tech.bugisberdagang;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by KurnhyGNEX on 26/12/2017.
*/
public class Session {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
// shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "snow-intro-slider";
private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";
public Session(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setFirstTimeLaunch(boolean isFirstTime) {
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
editor.commit();
}
public boolean isFirstTimeLaunch() {
return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);
}
}
when I insert this code in IntroActivity.java after super.onCreate
session = new Session(this);
if (!session.isFirstTimeLaunch()) {
launchHomeScreen();
finish();
}
private void launchHomeScreen() {
session.setFirstTimeLaunch(false);
startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
finish();
}
it's not working, please give me some advice
i have tried this , and it is working code :
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
public class WelcomeActivity extends AppCompatActivity {
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
private int[] layouts;
private Button btnSkip, btnNext;
private PrefManager prefManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Checking for first time launch - before calling setContentView()
prefManager = new PrefManager(this);
if (!prefManager.isFirstTimeLaunch()) {
launchHomeScreen();
finish();
}
// Making notification bar transparent
if (Build.VERSION.SDK_INT >= 21) {
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
}
setContentView(R.layout.activity_welcome);
viewPager = (ViewPager) findViewById(R.id.view_pager);
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
btnSkip = (Button) findViewById(R.id.btn_skip);
btnNext = (Button) findViewById(R.id.btn_next);
// layouts of all welcome sliders
// add few more layouts if you want
layouts = new int[]{
R.layout.welcome_slider_one,
R.layout.welcome_slider_two,
R.layout.welcome_slider_three,
R.layout.welcome_slider_four};
// adding bottom dots
addBottomDots(0);
// making notification bar transparent
changeStatusBarColor();
myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
btnSkip.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
launchHomeScreen();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = getItem(+1);
if (current < layouts.length) {
// move to next screen
viewPager.setCurrentItem(current);
} else {
launchHomeScreen();
}
}
});
}
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorsInactive[currentPage]);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive[currentPage]);
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
private void launchHomeScreen() {
prefManager.setFirstTimeLaunch(false);
startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
finish();
}
// viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
addBottomDots(position);
// changing the next button text 'NEXT' / 'GOT IT'
if (position == layouts.length - 1) {
// last page. make button text to GOT IT
btnNext.setText(getString(R.string.start));
btnSkip.setVisibility(View.GONE);
} else {
// still pages are left
btnNext.setText(getString(R.string.next));
btnSkip.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
/**
* Making notification bar transparent
*/
private void changeStatusBarColor() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
/**
* View pager adapter
*/
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public MyViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
container.addView(view);
return view;
}
#Override
public int getCount() {
return layouts.length;
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
}
activity_welcome.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.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<LinearLayout
android:id="#+id/layoutDots"
android:layout_width="match_parent"
android:layout_height="#dimen/dots_height"
android:layout_alignParentBottom="true"
android:layout_marginBottom="#dimen/dots_margin_bottom"
android:gravity="center"
android:orientation="horizontal" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_above="#id/layoutDots"
android:alpha=".5"
android:background="#android:color/white" />
<Button
android:id="#+id/btn_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#null"
android:text="#string/next"
android:textColor="#android:color/white" />
<Button
android:id="#+id/btn_skip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#null"
android:text="#string/skip"
android:textColor="#android:color/white" />
</RelativeLayout>
PrefManager class
public class PrefManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;
// shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "welcome";
private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";
public PrefManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setFirstTimeLaunch(boolean isFirstTime) {
editor.putBoolean(IS_FIRST_TIME_LAUNCH, isFirstTime);
editor.commit();
}
public boolean isFirstTimeLaunch() {
return pref.getBoolean(IS_FIRST_TIME_LAUNCH, true);
}
}
I'm trying to create a slider in Android Studio and encountered 2 errors in my code. Here is the first one.
Here is the error:
'error: ';' expected
This is the line in which the error occured
If (Build.VERSION.SDK_INT)=Build.VERSION_CODES.LOLLIPOP)
{
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
And the second error is this, but I don't have any idea where to look for this error since I'm just new to java and this is the first time I encountered this.
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
This is my complete code.
package mac.mac.dictionary;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity {
private Viewpager viewpager;
private Intromanager intromanager;
private ViewPagerAdapter viewPagerAdapter;
private TextView[] dots;
Button next,skip;
private LinearLayout dotsLayout;
private int[] layouts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
intromanager = new Intromanager(this);
if(!intromanager.Check())
{
intromanager.setFirst(false);
Intent i = new Intent(MainActivity.this, Main2Activity.class);
startActivity(i);
finish();
}
if(Build.VERSION.SDK_INT>=21)
{
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE|View.SYSTEM_UI_FLAG_FULLSCREEN);
}
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.view_pager);
dotsLayout=(LinearLayout)findViewById(R.id.LayoutDots);
skip=(Button)findViewById(R.id.btn_skip);
next=(Button)findViewById(R.id.btn_next);
layouts = new int[]{R.layout.activity_screen_1,R.layout.activity_screen_2,R.layout.activity_screen_3};
addBottomDots(0);
changeStatusBarColor();
viewPagerAdapter = new ViewPagerAdapter();
viewPager.setAdapter(viewPagerAdapter);
viewPager.addOnPageChangeListener(viewListener);
skip.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, Main2Activity.class);
startActivity(i);
finish();
}
});
next.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
int current = getItem(+1);
if(current<layouts.length)
{
viewpager.setCurrentItem(current);
}
else
{
Intent i = new Intent(MainActivity.this, Main2Activity.class);
startActivity(i);
finish();
}
}
});
}
private void addBottomDots(int position)
{
dots = new TextView[layouts.length];
int[] colorActive = getResources().getIntArray(R.array.dot_active);
int[] colorInactive = getResources().getIntArray(R.array.dot_inactive);
dotsLayout.removeAllViews();
for(int i=0; i<dots.length; i++)
{
dots[i]=new TextView(this);
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorInactive[position]);
dotsLayout.addView(dots[i]);
}
if(dots.length>0)
dots[position].setTextColor(colorActive[position]);
}
private int getItem(int i)
{
return viewPager.getCurrentItem() + 1;
}
Viewpager.OnPageChangeListener viewListener = new ViewPager.OnPageChangeListener()
{
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
addBottomDots(position);
if(position==layouts.length-1)
{
next.setText("PROCEED");
skip.setVisibility(View.GONE);
}
else
{
next.setText("NEXT");
skip.setVisibility(View.VISIBLE);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
private void changeStatusBarColor()
{
If (Build.VERSION.SDK_INT)=Build.VERSION_CODES.LOLLIPOP)
{
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
public class ViewPagerAdapter extends PagerAdapter
{
private LayoutInflater layoutInflater;
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = layoutInflater.inflate(layouts[position],container,false);
container.addView(v);
return v;
}
#Override
public int getCount() {
return layouts.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View v =(View)object;
container.removeView(v);
}
}
}
if (Build.VERSION.SDK_INT==Build.VERSION_CODES.LOLLIPOP)
try this
on the homepage of my app i have edittexts that represent counters for each row in my list. whenever i change activity and return back to my main screen all the numbers disappear, the same happens when I close the app and open it again. How do i make the numbers stay?
My main activity where I call the row layout with the edittexts
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MyActivity extends Activity implements MyAdapterInterface{
private CustomCursorAdapter customAdapter;
public ListView list1;
//instantiating the database class
com.example.rory.dripdrop.DBAdapter db = new com.example.rory.dripdrop.DBAdapter(this);
public MyActivity mMyActivity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
list1 = (ListView)findViewById(R.id.data_list);
db.open();
mMyActivity = this;
//button and listener for add activity
Button addBtn = (Button)findViewById(R.id.add);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Add.class);
startActivity(i);
}
});
//button and listener for delete activity
Button deleteBtn = (Button)findViewById(R.id.delete);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Delete.class);
startActivity(i);
}
});
//button and listener for update activity
Button updateBtn = (Button)findViewById(R.id.update);
updateBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MyActivity.this, Update.class);
startActivity(i);
}
});
try {
String destPath = "/data/data/" + getPackageName() + "/databases/AssignmentDB";
File f = new File(destPath);
if (!f.exists()) {
CopyDB( getBaseContext().getAssets().open("mydb"),
new FileOutputStream(destPath));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//handler function for custom adapter, found example online to help with this
new Handler().post(new Runnable() {
#Override
public void run() {
customAdapter = new CustomCursorAdapter(MyActivity.this, db.getAllRecords(), mMyActivity);
list1.setAdapter(customAdapter);
}
});
}
public void onResume()
{
super.onResume();
//update list
addData();
}
//refreshes data base when main page is resumed
public void addData()
{
//handler function for custom adapter, found example online to help with this
new Handler().post(new Runnable() {
#Override
public void run() {
customAdapter = new CustomCursorAdapter(MyActivity.this, db.getAllRecords(), mMyActivity);
list1.setAdapter(customAdapter);
}
});
}
//chaning the running total
public void updateLitres(int value)
{
EditText editLitres = (EditText)findViewById(R.id.edit1);
//EditText myEditText2 = (EditText)findViewById(R.id.edit2);
editLitres.setText(String.valueOf(value));
//myEditText2.setText(String.valueOf(value));
}
public void updateCost(double value)
{
EditText editCost = (EditText)findViewById(R.id.edit2);
String.format("%.2f", value);
editCost.setText("€" + String.valueOf(value));
}
private class DBAdapter extends BaseAdapter {
private LayoutInflater mInflater;
//private ArrayList<>
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
return null;
}
}
public void CopyDB(InputStream inputStream, OutputStream outputStream)
throws IOException {
//---copy 1K bytes at a time---
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
inputStream.close();
outputStream.close();
}
}
My custom adapter for the rows
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomCursorAdapter extends CursorAdapter {
//public int counter = 0;
public ArrayList<Integer> counter;
public ArrayList<Integer> counter2;
private MyAdapterInterface mMyInterface;
public CustomCursorAdapter(Context context, Cursor cursor, MyAdapterInterface myInterface) {
//instantiating the values
super(context, cursor);
this.context = context;
this.mMyInterface = myInterface;
//array to sort each value per row
counter = new ArrayList<Integer>();
counter2 = new ArrayList<Integer>();
//default all counters to 0
for(int i=0; i<cursor.getCount(); i++)
{
counter.add(0);
counter2.add(0);
}
}
Context context;
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// when the view will be created for first time,
// we need to tell the adapters, how each item will look
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.row, parent, false);
return retView;
}
public void bindView(View view, Context context, final Cursor cursor) {
//getting the first value for the custom row (the item name)
TextView textViewItemName = (TextView) view.findViewById(R.id.item1);
textViewItemName.setText(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(1))));
final int litres = Integer.parseInt(cursor.getString(cursor.getColumnIndex(cursor.getColumnName(2))));
//editText for custom row
final EditText runningTotal = (EditText) view.findViewById(R.id.runningTotal);
//setting up the plus button
final Button plusButton = (Button)view.findViewById(R.id.plusButton);
plusButton.setOnClickListener(new View.OnClickListener() {
private int counterPos;
private int counter2;
public void onClick(View v) {
//code to change the value of the editText and the array, not working
//cursor.getPosition() returns the position in the list
counterPos = counter.get(cursor.getPosition());
//increments the number at counterPos
counterPos = counterPos + litres;
//incrementing the edittext
//counter2 = counter.get(cursor.getPosition());
counter2++;
//set the new value to the array position
counter.set(cursor.getPosition(), counterPos);
//changes the editText in middle of row
runningTotal.setText(Integer.toString(counter2));
//sends counterPos to the interface for the running total
mMyInterface.updateLitres(counterPos);
mMyInterface.updateCost(counterPos * 0.00488);
}
});
//setting up the minus button
final Button minusButton = (Button)view.findViewById(R.id.minusButton);
minusButton.setOnClickListener(new View.OnClickListener() {
private int counterPos = 0;
private int counter2;
public void onClick(View v) {
//code to change the value of the editText and the array, not working
counterPos = counter.get(cursor.getPosition());
//increments the number at counterPos
counterPos = counterPos + litres;
//incrementing the edittext
//counter2 = counter.get(cursor.getPosition());
counter2--;
//set the new value to the array position
counter.set(cursor.getPosition(), counterPos);
//changes the editText in middle of row
runningTotal.setText(Integer.toString(counter2));
//sends counterPos to the interface for the running total
mMyInterface.updateLitres(counterPos);
mMyInterface.updateCost(counterPos * 0.00488);
}
});
}
}
You should have a look here You should take a look at the shared preferences, http://developer.android.com/reference/android/content/SharedPreferences.html, I used this and helped me get through it, You need to save each edit text that you want to save. and as for each row I would suggest making an array or loop for saving the edit boxes in the rows
didn't read your code bro, but answering in concern to your question title :
override onStop and save the data to Shared Preferences, its very easy to use:
//To save your data
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();
//to extract your data in onCreate or whenever you feel like:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
You will want to look into SharedPreferences, once you do you will basically be saving your values in SharedPreferences in an onPause() / onDestroy() method, and then in your onResume() / onCreate() methods you will retrieve the previously stored data
Edit: You can retrieve a string from an EditText in the following way
String toStore = EditText.getText().toString();
and then store it
getSharedPreferences("PREFERENCE",MODE_PRIVATE).edit().putString("KEY", toStore);
so...
public void onPause(){
super.onPause();
String toStore = EditText.getText().toString();
getSharedPreferences("PREFERENCE",MODE_PRIVATE).edit().putString("KEY", toStore);
}
public void onResume(){
super.onResume();
String toStore = PreferenceManager.getDefaultSharedPreferences(context).getString("KEY", "defaultStringIfNothingFound");
EditText.setText(toStore);
}
You may use onSavedInstanceState and onRestoreInstanceState methods of activity !
So in onSavedInstanceState (called before your activity pauses) you may save your `EditText' values to the bundle,
And restore them back in onRestoreInstance state.
You can use the link by #Kaique for more reference,
and also this answer https://stackoverflow.com/a/16769864/826657 and all related answers here.
You should take a look at the shared preferences, http://developer.android.com/reference/android/content/SharedPreferences.html