How to save string sets to Shared Preferences - java

I have been able to save one entry to shared preferences and for it to display in a list view on another view but I am wanting to add multiple entries and them to display in the listview too. I thought I had the correct code but it doesn't see mto have changed anything. My intent is a favourites list, I take the entry data from one view and display it in another view.
SingleView Activity:
SharedPreferences.Editor fd;
SharedPreferences FeedPref;
private ArrayList<String> addArray = new ArrayList<>();
txt = (TextView) findViewById(R.id.name);
add = (Button) findViewById(R.id.btnAdd);
FeedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
fd = FeedPref.edit();
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String message = txt.getText().toString();
if (addArray.contains(message)) {
Toast.makeText((getBaseContext()), "Plant Already Added", Toast.LENGTH_LONG).show();
} else {
addArray.add(message);
FeedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
fd = FeedPref.edit();
fd.putInt("array_size", addArray.size());
for (int i = 0; i < addArray.size(); i++) {
fd.putString("Status_" + i, addArray.get(i));
}
fd.commit();
Toast.makeText((getBaseContext()), "Plant Added", Toast.LENGTH_LONG).show();
}
}
});
}
mygarden activity:
public class mygardenMain extends Activity {
//String[] presidents;
ListView listView;
//ArrayAdapter<String> adapter;
SharedPreferences FeedPref;
SharedPreferences.Editor fd;
//private ArrayList<String> addArray;
//public static final String PREFS = "examplePrefs";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mygarden_list);
listView = (ListView) findViewById(R.id.mygardenlist);
//addArray = new ArrayList<>();
FeedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
int size = FeedPref.getInt("array_size", 0);
for (int i = 0; i < size; i++) {
String mess = FeedPref.getString("Status_" + i, null);
String[] values = new String[]{mess};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
listView.setAdapter(adapter);
}
}

Set abc = new HashSet<>();
abc.add("john");
abc.add("test");
abc.add("again");
SharedPreferences sharedPref = this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putStringSet("key",abc);
editor.commit();

SingleView Activity:
SharedPreferences.Editor fd;
SharedPreferences FeedPref;
private ArrayList<String> addArray = new ArrayList<>();
txt = (TextView) findViewById(R.id.name);
add = (Button) findViewById(R.id.btnAdd);
FeedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
fd = FeedPref.edit();
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String message = txt.getText().toString();
if (addArray.contains(message)) {
Toast.makeText((getBaseContext()), "Plant Already Added", Toast.LENGTH_LONG).show();
} else {
FeedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
fd = FeedPref.edit();
Gson gson = new Gson();
String jsonText = Prefs.getString("key", "");
if(!jsonText.equals(""))
{
String[] text = gson.fromJson(jsonText, String[].class); //EDIT: gso to gson
if(text.length>0)
{
//addArray = Arrays.asList(text);
//addArray = new ArrayList(addArray);
List<String> addArrayNew = Arrays.asList(text);
addArray = new ArrayList(addArrayNew);
}
}
addArray.add(message);
gson = new Gson();
jsonText = gson.toJson(addArray );
prefsEditor.putString("key", jsonText);
prefsEditor.commit();
}
});
}
mygarden activity:
public class mygardenMain extends Activity {
//String[] presidents;
ListView listView;
//ArrayAdapter<String> adapter;
SharedPreferences FeedPref;
SharedPreferences.Editor fd;
//private ArrayList<String> addArray;
//public static final String PREFS = "examplePrefs";
String jsonText;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mygarden_list);
listView = (ListView) findViewById(R.id.mygardenlist);
//addArray = new ArrayList<>();
FeedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
int size = FeedPref.getInt("array_size", 0);
Gson gson = new Gson();
jsonText = FeedPref.getString("key", "");
if(!jsonText.equals(""))
{
String[] values= gson.fromJson(jsonText, String[].class);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
listView.setAdapter(adapter);
}
}

Related

How to stop replacing previous entries in shared preferences?

My code used to replace the previous entries and I realized I needed to use different keys for storing in shared preferences. Now my code does not output anything in the listview. please help
Java code where I ask for information about the person (name, favcolor, favfood)
public class personInfo extends AppCompatActivity {
EditText editText_name;
EditText editText_favfood;
EditText editText_favcolor;
Button button_save;
static int count = 0;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_personinfo);
Log.d(MainActivity.class.getSimpleName(), "onCreate");
editText_name = (EditText) findViewById(R.id.editText_name);
editText_favcolor = (EditText) findViewById(R.id.editText_favcolor);
editText_favfood = (EditText) findViewById(R.id.editText_favfood);
button_save = (Button) findViewById(R.id.button_save);
button_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
count++;
SharedPreferences sharedPreferences = getSharedPreferences("ENTRIES", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("name" + count, editText_name.getText().toString());
editor.putString("favcolor" + count, editText_favcolor.getText().toString());
editor.putString("favfood" + count, editText_favfood.getText().toString());
editor.apply();
editor.putInt("numOfEntries", count);
Intent it = new Intent(personInfo.this, listOfPeople.class);
startActivity(it);
}
});
}
}
Java code, page that is supposed to display the entries
public class listOfPeople extends AppCompatActivity {
ListView listView;
ArrayList<listEntry> list = new ArrayList<>();
listEntry le;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
listView = (ListView) findViewById(R.id.listView_persons);
SharedPreferences sharedPreferences = getSharedPreferences("ENTRIES", MODE_PRIVATE);
int count = sharedPreferences.getInt("numOfEntries", 0);
for(int i = 1; i <= count; i++){
String nameValue = sharedPreferences.getString("name" + i, "");
String favcolorValue = sharedPreferences.getString("favcolor" + i, "");
String favfoodValue = sharedPreferences.getString("favfood" + i, "");
le = new listEntry(nameValue, favcolorValue, favfoodValue);
list.add(le);
}
personListAdapter adapter = new personListAdapter(this, R.layout.entryrow, list);
listView.setAdapter(adapter);
}
}
You are applying (saving) preferences before putting count
editor.apply();
editor.putInt("numOfEntries", count);
Just put before applying
editor.putInt("numOfEntries", count);
editor.apply();
call editor.apply() after editor.putInt("numOfEntries", count);
editor.putInt("numOfEntries", count);
editor.apply();

I have questions about ListView and SharedPreference

I am a beginner developer who is studying Android.
The function I want to develop is "Save the data entered in EditText as JSON, save it as SharedPreference, and output it to ListView".
To save it as SharedPreference is OK, but, To output it to ListView is not working now.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private ListView listView;
private Button save_btn;
private ArrayList<List> data = new ArrayList<List>();
ListAdapter adapter;
String title="";
String info="";
int img = R.drawable.man;
String jsondata;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
save_btn = (Button) findViewById(R.id.button1);
loadArrayList(getApplicationContext());
adapter = new ListAdapter(this, R.layout.row, data);
listView.setAdapter(adapter);
registerForContextMenu(listView);
save_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View dlgview = View.inflate(MainActivity.this, R.layout.adds, null);
//adds.xml
final EditText et_title = (EditText) dlgview.findViewById(R.id.editText1);
final EditText et_info = (EditText) dlgview.findViewById(R.id.editText2);
ImageView img1 = (ImageView) dlgview.findViewById(R.id.imageView2);
AlertDialog.Builder dlg = new AlertDialog.Builder(MainActivity.this);
dlg.setTitle("ADD");
dlg.setView(dlgview);
dlg.setNegativeButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
try{
jsonObject.put("title", et_title.getText().toString());
jsonObject.put("info", et_info.getText().toString());
jsonObject.put("image",img);
jsonArray.put(jsonObject);
} catch (JSONException e){
e.printStackTrace();
}
jsondata = jsonArray.toString();
saveArrayList();
adapter.notifyDataSetChanged();
}
});
dlg.setPositiveButton("Cancel",null);
dlg.show();
}
});
}//End of onCreate
private void saveArrayList(){
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putString("jsonData", jsondata);
Log.i("moi","get Data test : " + "jsonData");
editor.apply();
}
private void loadArrayList(Context context){
SharedPreferences sharedPrefs2 = PreferenceManager.getDefaultSharedPreferences(context);
int size = sharedPrefs2.getInt("appreciation_size",0);
String strJson = sharedPrefs2.getString("jsonData", "fail");
Log.i("moi","get SharedPreferences test : " + strJson);
if (strJson != "fail")
{
try {
JSONArray response = new JSONArray(strJson);
for (int i=0; i<size; i++)
{
JSONObject jsonobject = response.getJSONObject(i);
title = jsonobject.getString("title");
Log.i("moi","title test : " + "title");
info = jsonobject.getString("info");
Log.i("moi","info test : " + "info");
data.add(new List(title, info, img));
}
adapter = new ListAdapter(getApplicationContext(), R.layout.row, data);
listView.setAdapter(adapter);
} catch (JSONException e){
e.printStackTrace();
}
}
}
}//End of class
Because you just called loadArrayList() once in onCreate(). That means your data in adapter just changes once.
you call adapter.notifyDataSetChanged() but this method doesnt callloadArrayList()`.
so try to save new json into data in onClick()
Try to remove your code:
adapter = new ListAdapter(this, R.layout.row, data);
listView.setAdapter(adapter);
in CreateView.
I think you set adapter listview double.
i hope that helps you.. thanks

Struggling with getting data from another activity

I can transfer my array-data from an activity to the other, but not my string-data, and I don't know why.
This is my mainActivity:
protected void onClickCityBreak(View v) {
persons = (EditText) findViewById(R.id.txtPerson);
days = (EditText) findViewById(R.id.txtDays);
String p = persons.toString();
String d = days.toString();
String [] arrayCityBreak = getResources().getStringArray(R.array.citybreak);
Intent myintent = new Intent(MainActivity.this, TripActivity.class);
myintent.putExtra("PERSONS", p);
myintent.putExtra("DAYS", d);
myintent.putExtra("PLACES",arrayCityBreak);
startActivity(myintent);
}
This is my other activity I am sending to:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trip);
String person = getIntent().getStringExtra("PERSONS");
String day = getIntent().getStringExtra("DAYS");
TextView txtPerson = (TextView) findViewById(R.id.txtViewPersons);
txtPerson.setText("Persons travelling: " + person);
TextView txtDay = (TextView) findViewById(R.id.txtViewDays);
txtDay.setText("Days of traveling: " + day);
String[] arrayCityBreak = getIntent().getStringArrayExtra("PLACES");
ArrayAdapter<String> adapterCityBreak = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayCityBreak);
ListView myview = (ListView) findViewById(R.id.lstView);
myview.setAdapter(adapterCityBreak);
}
I get this on my TextView in the application:
android.support.v7.widget.AppCompactEditText{13e7726VFED...CL. ........563,56....#7f0c0059 app:id/txtDays\
The same for txtPerson.
I have also tried using Bundle
Getting the content of an EditText should be done in this way :
String p = persons.getText().toString();
String d = days.getText().toString();
Also if you have another problems with putExtra, you can do something like this:
MainActivity:
protected void onClickCityBreak(View v) {
persons = (EditText) findViewById(R.id.txtPerson);
days = (EditText) findViewById(R.id.txtDays);
String p = persons.getText().toString();
String d = days.getText().toString();
String [] arrayCityBreak = getResources().getStringArray(R.array.citybreak);
Intent myintent = new Intent(MainActivity.this, TripActivity.class);
AnotherActivityClass secondactivity = new AnotherActivityClass();
secondactivity.persons = p;
secondactivity.days = d;
secondactivity.places = arrayCityBreak;
startActivity(myintent);
}
Create public string persons and days, also create public String[] in SecondActivity:
public String days;
public String persons;
public String [] places;
And then in SecondActivity use this values:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trip);
TextView txtPerson = (TextView) findViewById(R.id.txtViewPersons);
txtPerson.setText("Persons travelling: " + person);
TextView txtDay = (TextView) findViewById(R.id.txtViewDays);
txtDay.setText("Days of traveling: " + day);
ArrayAdapter<String> adapterCityBreak = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayCityBreak);
ListView myview = (ListView) findViewById(R.id.lstView);
myview.setAdapter(adapterCityBreak);
}

How to solve the error like java.lang.Throwable: setStateLocked?

I am developing an app. In it I'm using a listview. When I click on list item, it should go to next activity, i.e ProfileActivity2.java. It works fine, but in this ProfileActivty2 there is a button at the bottom and when I click on this button my app gets crashed and stopped in listview page. And shows the error java.lang.Throwable: setStateLocked in listview layout file i.e At setContentView. How do I solve this error?
//ProfileActivity2.java
public class ProfileActivity2 extends AppCompatActivity {
//Textview to show currently logged in user
private TextView textView;
private boolean loggedIn = false;
Button btn;
EditText edname,edaddress;
TextView tvsname, tvsprice;
NumberPicker numberPicker;
TextView textview1,textview2;
Integer temp;
String pname, paddress, email, sname, sprice;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile1);
//Initializing textview
textView = (TextView) findViewById(R.id.textView);
edname=(EditText)findViewById(R.id.ed_pname);
edaddress=(EditText)findViewById(R.id.ed_add);
tvsname=(TextView)findViewById(R.id.textView_name);
tvsprice=(TextView)findViewById(R.id.textView2_price);
btn=(Button)findViewById(R.id.button);
Intent i = getIntent();
// getting attached intent data
String name = i.getStringExtra("sname");
// displaying selected product name
tvsname.setText(name);
String price = i.getStringExtra("sprice");
// displaying selected product name
tvsprice.setText(price);
numberPicker = (NumberPicker)findViewById(R.id.numberpicker);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(4);
final int foo = Integer.parseInt(price);
textview1 = (TextView)findViewById(R.id.textView1_amount);
textview2 = (TextView)findViewById(R.id.textView_seats);
// numberPicker.setValue(foo);
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
temp = newVal * foo;
// textview1.setText("Selected Amount : " + temp);
// textview2.setText("Selected Seats : " + newVal);
textview1.setText(String.valueOf(temp));
textview2.setText(String.valueOf(newVal));
// textview1.setText(temp);
// textview2.setText(newVal);
}
});
//Fetching email from shared preferences
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// submitForm();
// Intent intent = new Intent(ProfileActivity2.this, SpinnerActivity.class);
// startActivity(intent);
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
String email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "Not Available");
textView.setText(email);
if(loggedIn){
submitForm();
Intent intent = new Intent(ProfileActivity2.this, SpinnerActivity.class);
startActivity(intent);
}
}
});
}
private void submitForm() {
// Submit your form here. your form is valid
//Toast.makeText(this, "Submitting form...", Toast.LENGTH_LONG).show();
String pname = edname.getText().toString();
String paddress = edaddress.getText().toString();
String sname = textview1.getText().toString();
// String sname= String.valueOf(textview1.getText().toString());
String sprice= textview2.getText().toString();
// String sprice= String.valueOf(textview2.getText().toString());
String email= textView.getText().toString();
Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new SignupActivity(this).execute(pname,paddress,sname,sprice,email);
}
}
//SignupActivity
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
Boolean error, success;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String pname = arg0[0];
String paddress = arg0[1];
String sname = arg0[2];
String sprice = arg0[3];
String email = arg0[4];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?pname=" + URLEncoder.encode(pname, "UTF-8");
data += "&paddress=" + URLEncoder.encode(paddress, "UTF-8");
data += "&sname=" + URLEncoder.encode(sname, "UTF-8");
data += "&sprice=" + URLEncoder.encode(sprice, "UTF-8");
data += "&email=" + URLEncoder.encode(email, "UTF-8");
link = "http://example.in/Spinner/update.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
// return new String("Exception: " + e.getMessage());
// return null;
}
return null;
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
Log.e("TAG", jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Success! Your are Now MangoAir User.", Toast.LENGTH_LONG).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Looks Like you already have Account with US.", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
// Toast.makeText(context, "Error parsing JSON Please data Fill all the records.", Toast.LENGTH_SHORT).show();
// Toast.makeText(context, "Please LogIn", Toast.LENGTH_SHORT).show();
Toast.makeText(context, "Please Login", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "Grrr! Check your Internet Connection.", Toast.LENGTH_SHORT).show();
}
}
}
//List_Search
public class List_Search extends AppCompatActivity {
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String SNAME = "sname";
static String SPRICE = "sprice";
Context ctx = this;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.list_search);
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(List_Search.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://example.in/MangoAir_User/mangoair_reg/ListView1.php");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("result");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("sname", jsonobject.getString("sname"));
map.put("sprice", jsonobject.getString("sprice"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} 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.listView_search);
// Pass the results into ListViewAdapter.java
// adapter = new ListViewAdapter(List_Search.this, arraylist);
adapter = new ListViewAdapter(ctx, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
//ListViewAdapter
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
private boolean loggedIn = false;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView name,price;
Button btn;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.search_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
name = (TextView) itemView.findViewById(R.id.textView8_sellernm);
// Capture position and set results to the TextViews
name.setText(resultp.get(List_Search.SNAME));
price = (TextView) itemView.findViewById(R.id.textView19_bprice);
// Capture position and set results to the TextViews
price.setText(resultp.get(List_Search.SPRICE));
btn=(Button)itemView.findViewById(R.id.button3_book);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resultp = data.get(position);
Intent intent = new Intent(context, ProfileActivity2.class);
// Pass all data rank
intent.putExtra("sname", resultp.get(List_Search.SNAME));
intent.putExtra("sprice", resultp.get(List_Search.SPRICE));
context.startActivity(intent);
}
});
return itemView;
}
}
context.startActivity(intent);
I think the error is at this line inside btn.setOnClickListener of getview block just use startActivity(intent);

How to resolve the following error Product() in Product cannot be applied?

Here i have declared the product class variables and assigned it.
product.java
public class Product {
String[] name= new String[100];
int price;
int image;
boolean box;
Product(String[] _describe, int _price, int _image, boolean _box) {
name = _describe;
price = _price;
image = _image;
box = _box;
}
}
This is my product class. What should i change in the above coding??
public class MainActivity extends Activity {
String[] data =new String[] {"no:1","no:2","no:3","no:4","no:5","no:6"};
String[] columnTags = new String[] {"ProcessName", "IpItem", "IpColor", "OpItem","OpColor", "PlanQty", "DcQty", "RecQty", "RtQty"};
ArrayList products = new ArrayList();
ListAdapter1 boxAdapter;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fillData();
boxAdapter = new ListAdapter1(this, products);
ListView lvMain = (ListView) findViewById(R.id.lvMain);
lvMain.setAdapter(boxAdapter);
}
void fillData() {
for (int i = 0; i <= 20; i++) {
products.add(new Product(columnTags, i * 100,i * 553
, false));
}
}
public void showResult(View v) {
String result = "Selected Product are :";
int totalAmount=0;
for (Product p : boxAdapter.getBox()) {
if (p.box){
result += "\n" + p.name;
totalAmount+=p.image;
}
}
String total="Total="+totalAmount;
// Toast.makeText(this, result+"\n"+"Total Amount:="+totalAmount, Toast.LENGTH_LONG).show();
Bundle bundle=new Bundle();
bundle.putString("res",result);
bundle.putString("tot",total);
Intent intent = new Intent(MainActivity.this,MainActivity2Activity.class);
intent.putExtras(bundle);
startActivity(intent);
}
}
The first parameter of your add() requires a String[] and you are passing it a String.
Just change ,
products.add(columnTags[i],i*100,i*553,false)
to
products.add(columnTags,i*100,i*553,false)
Also do the following,
for(...)
{
String temp = columnTags[i];
products.add(temp,i*100,i*553,false)
}
EDIT
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fillData();
ArrayAdapter boxAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, new ArrayList<String>(Arrays.asList(products.name)));
ListView lvMain = (ListView) findViewById(R.id.lvMain);
lvMain.setAdapter(boxAdapter);
}
void fillData() {
String temp;
for (int i = 0; i <columnTags.length; i++) {
temp = columnTags[i];
products.add(new Product(temp, i * 100,i * 553, false));
}
}

Categories

Resources