To pass the values of json array in listview - android

i'm working on a student record project And there are four fields in it like class name roll no. marks and User is putting data into it by edit text
and i'm storing the values into the json Array . Also i'm putting values in array list and i'm passing to my fragment class .
New record class
public class newrecord extends Activity {
public final static String TAG = "SomeValue";
Button but;
EditText roll, name, marks, Class;
TextView text;
String rollno, nameno, classno, marksno;
TopRatedFragment frags;
public static final String ROLL_key = "roll number";
public static final String NAME_key = "Name";
public static final String Class_key = "Class";
public static final String MARKS_key = "marks";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newrecord);
final newrecord rd = new newrecord();
// data = new dbbase(getApplicationContext());
text = (TextView) findViewById(R.id.textviewenter);
roll = (EditText) findViewById(R.id.editRollno);
name = (EditText) findViewById(R.id.editName);
marks = (EditText) findViewById(R.id.editMarks);
Class = (EditText) findViewById(R.id.edittextclass);
but = (Button) findViewById(R.id.btnadd);
frags = new TopRatedFragment();
final JSONArray ary = new JSONArray();
final JSONObject obj = new JSONObject();
but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View V) {
try {
obj.put("Roll No", roll.getText().toString());
obj.put("name", name.getText().toString());
obj.put("marks", marks.getText().toString());
obj.put("Class", Class.getText().toString());
ary.put(obj);
rd.nameno = name.getText().toString();
rd.rollno = roll.getText().toString();
rd.marksno = marks.getText().toString();
rd.classno = Class.getText().toString();
Log.d(TAG, "Values Inserted");
} catch (Exception e) {
text.setText("error");
}
ArrayList<String> list_list = new ArrayList<String>();
list_list.add(rollno);
list_list.add(nameno);
list_list.add(classno);
list_list.add(marksno);
Intent i = new Intent(newrecord.this, MainActivity.class);
// Bundle b = new Bundle();
i.putStringArrayListExtra("fite", list_list);
startActivity(i);
}
});
}
public ArrayList<HashMap<String, String>> Getalldata() {
ArrayList<HashMap<String, String>> dude;
dude = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put(ROLL_key, rollno);
map.put(NAME_key, nameno);
map.put(Class_key, classno);
map.put(MARKS_key, marksno);
dude.add(map);
return dude;
}
}
And i want to return list in the listview in my fragment .
As in the values that i add in edittexts should appear in the list in my fragment class.
My topfragment class
public class TopRatedFragment extends Fragment {
ListView List;
ListAdapter mAdapter;
int nr = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated,
container, false);
Intent in = new Intent();
newrecord record = new newrecord();
String tim = in.getStringExtra("fite");
ArrayList<String> liist = new ArrayList<String>();
if (liist.size() == 0) {
liist.add("Template1");
} else {
liist=in.getStringArrayListExtra("fite")
}
List = (ListView) rootView.findViewById(R.id.listView1);
List.setAdapter(mAdapter);
mAdapter = new SelectionAdapter(getActivity(), R.layout.simplerow,
R.id.rowTextView, liist);
List.setAdapter(mAdapter);
List.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
// TODO Auto-generated method stub
((BaseAdapter) mAdapter).notifyDataSetChanged();
}
});

Try this out:
In NewRecord class
Intent menulist = new Intent(this, cart_activity.class);
menulist.putExtra("cartlist", cart_Array_List);
startActivity(menulist);
In your fragment:
intent = getIntent();
if (intent != null) {
arr_cart_items = (ArrayList<HashMap<String, String>>) intent
.getSerializableExtra("cartlist");
}
Make sure your ArrayList is not empty.
And one common mistake that I used to do was to set text color as white, so the contents of the listview was not actually visible. So please check that too.

Change this line
Intent in = new Intent();
To
Intent in = getActivity().getIntent();
I hope this one will help you :)

Related

android send data in listview to server

I retrieved some data from server and populated these data into a listview. I want to use part of the data i received and send it back to server. How do I do it? When I click on one of the list item it will start another activity with buttons, when i click one of the button the app will use part of the data in that listitem(which was previously retrieved from server) and send it back to server. I'm new to android programming, i'm stuck and have no idea how do I do this. Could someone advised me? I know how to send data to server by manually typing the data i want to send.
This is how i get the data from server and populated into a listview and i want to send a particular phonenumber received back to server when i click that listview item:
public class TabActivityQueue extends Fragment {
ListView list;
TextView number;
TextView info;
TextView remark;
TextView statuss;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//URL to get JSON Array
private static String url = "http://172.22.85.235:8080/Qproject/servlet/Qaction?action_flag=find";
//JSON Node Names
private static final String Table2 = "table2";
private static final String phonenumber = "phonenumber";
private static final String peoplenumber = "peoplenumber";
private static final String remarks = "remarks";
private static final String status = "status";
JSONArray table2 = null;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
//This layout contains your list view
View view = inflater.inflate(R.layout.activity_tab_activity_queue, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)getView().findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
public ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
number = (TextView)getView().findViewById(R.id.number);
info = (TextView)getView().findViewById(R.id.info);
remark = (TextView)getView().findViewById(R.id.remark);
statuss = (TextView)getView().findViewById(R.id.statuss);
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
public JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
public void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
table2 = json.getJSONArray(Table2);
for(int i = 0; i < table2.length(); i++){
JSONObject c = table2.getJSONObject(i);
// Storing JSON item in a Variable
String number = c.getString(phonenumber);
String info = c.getString(peoplenumber);
String remark = c.getString(remarks);
String statuss = c.getString(status);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(phonenumber, number);
map.put(peoplenumber, info);
map.put(remarks, remark);
map.put(status, statuss);
oslist.add(map);
list=(ListView)getView().findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(getActivity(), oslist,
R.layout.list_view,
new String[] { phonenumber,peoplenumber, remarks,status }, new int[] {
R.id.number,R.id.info, R.id.remark,R.id.statuss});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Toast.makeText(getActivity(), "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
Intent ThreeButton = new Intent(getActivity(), ThreeButton.class);
startActivity(ThreeButton);
}
}
);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent ThreeButton = new Intent(getActivity(), ThreeButton.class);
ThreeButton.putExtra("phone", oslist.get(position).get("phonenumber"));
//u can put all variables similarly...
startActivity(ThreeButton);
}
}
);
In ThreeButton Activity
onCreate(){
Intent data=getIntent();
data.getString("phone");
Log.v("phone",phone);
}
You do not have access to data in listview in your next activity. Instead of trying get that from there, you can pass needed data to new activity. Before call startActivity put into intent data using methods putExtra. By the way, if you are working with JSON you should check Gson library to parse json

how can i add items to an list view with custom adapter each time i click on the button?

what i am trying to do is something look like add to cart thing but on my android app , first of all i have add to cart activity which has all the values i need when i press the button i send my data as put extra to cartList Activity and it display on row and each time i press the button on some item it clear the array and display only one row ! but what i really need to do is when each time i press the button i want it to add on the previous items and display them all .. here is my add to cart activity :
public class AddToCart extends Activity{
EditText quantity=null;
TextView total=null;
TextView name=null;
TextView price=null;
TextView ava=null;
double totalprice=0.0;
ArrayList<String> listOfItemNames = new ArrayList<String>();
List<listClass>testList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.info);
Intent test = getIntent();
Intent intent = getIntent();
final String itemprice = intent.getStringExtra("price");
final String itemname = intent.getStringExtra("item");
final String itemava = intent.getStringExtra("ava");
final int imagehandler=intent.getIntExtra("image", 0);
Log.e("image handler",imagehandler+"");
name=(TextView)findViewById(R.id.textView2);
price=(TextView)findViewById(R.id.textView4);
total=(TextView)findViewById(R.id.textView7);
ava=(TextView)findViewById(R.id.textView9);
quantity=(EditText)findViewById(R.id.editText1);
Button addtocart=(Button)findViewById(R.id.button1);
ImageView imageview=(ImageView)findViewById(R.id.imageView1);
name.setText(itemname);
price.setText(itemprice);
ava.setText(itemava);
imageview.setImageResource(imagehandler);
addtocart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final String quantityvalue=quantity.getText().toString();
CharSequence currentavaiable=ava.getText();
int currentava=Integer.parseInt((String) currentavaiable);
Editable checked = quantity.getText();
String checkquantity=checked.toString();
Log.e("checked ",checked+"");
Log.e("check quantity",checkquantity);
try{
if(checkquantity==null){
Toast.makeText(AddToCart.this,"please enter quantity for your item", Toast.LENGTH_LONG).show();
}
else{
int x=0;
double y=0.0;
// String xvalue=quantity.getText().toString();
x = Integer.parseInt(quantityvalue);
Log.e("x",x+"");
y = Double.parseDouble(itemprice);
Log.e("x",x+"");
Log.e("y",y+"");
totalprice=x*y;
total.setText(totalprice+"");
Toast.makeText(AddToCart.this,"your item added succesfully !", Toast.LENGTH_LONG).show();
}
Intent newintent=new Intent(AddToCart.this,CartList.class);
newintent.putExtra("itemname",itemname);
newintent.putExtra("itemprice",itemprice);
newintent.putExtra("itemquantity",quantityvalue);
newintent.putExtra("totalprice",totalprice);
newintent.putExtra("image", imagehandler);
startActivity(newintent);
}//view
catch(Exception e){
e.printStackTrace();
}
}
});
}
}
and here is cart list class :
public class CartList extends Activity {
ListView list;
List<CartItems> detailsList = new ArrayList<CartItems>();
ArrayList<String> listtest=new ArrayList <String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.cart_list);
initializeComponents();
detailsList = SetAdapterList();
CustomAdapter adapter=new CustomAdapter(this,detailsList);
list.setAdapter(adapter);
}
private void initializeComponents()
{
list=(ListView)findViewById(R.id.listView1);
}
private List<CartItems> SetAdapterList()
{
// TODO Auto-generated method stub
CartItems details;
List<CartItems> detailsList = new ArrayList<CartItems>();
try{
Intent newintent = getIntent();
final String itemname = newintent.getStringExtra("itemname");
final String itemprice = newintent.getStringExtra("itemprice");
final String itemquantity = newintent.getStringExtra("itemquantity");
final double totalprice = newintent.getDoubleExtra("totalprice", 0.0);
String totprice=String.valueOf(totalprice);
// ArrayList <String> itemnames=new ArrayList<String>();
listtest.add(itemname);
Log.e("listtest",listtest+"");
final int imagehandler=newintent.getIntExtra("image", 0);
Log.e("image handler",imagehandler+"");
for(int i = 0; i< listtest.size(); i++)
{
details = new CartItems(itemname,itemprice,itemquantity,totprice,imagehandler);
detailsList.add(details);
}
}
catch(Exception e){
e.printStackTrace();
}
return detailsList;
}
}
and here is my custom adapter :
public class CustomAdapter extends ArrayAdapter<CartItems> {
Context context;
List<CartItems>Clist = new ArrayList<CartItems>();
public CustomAdapter(Context context, List<CartItems> detailsList) {
super(context, R.layout.single_row, R.id.textView1, detailsList);
// TODO Auto-generated constructor stub
this.context=context;
this.Clist = detailsList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row=inflater.inflate(R.layout.single_row, parent,false);
ImageView myimage=(ImageView) row.findViewById(R.id.imageView1);
TextView items=(TextView)row.findViewById(R.id.textView1);
TextView totalprice=(TextView)row.findViewById(R.id.textView2);
items.setText(Clist.get(position).getItemName());
totalprice.setText(Clist.get(position).getTotalPrice());
myimage.setImageResource(Clist.get(position).getImage());
return row;
}
}
here is my itemcart class :
public class CartItems {
private String itemName;
private String itemPrice;
private String Quantity;
private String totalPrice;
private int image;
public CartItems(String itemname,String itemprice, String quantity, String totalprice2, int image){
this.itemName=itemname;
this.itemPrice=itemprice;
this.Quantity=quantity;
this.totalPrice=totalprice2;
this.image=image;
}
//getter and setters
}
please can anyone help me?? i am so despaired !!
You are resetting you arraylist everyime. Instead you add item to it each time you select an item. Follow these steps:
1)change your setadapter function to return item, not itemlist.
private CartItems SetAdapterList()
{
// TODO Auto-generated method stub
CartItems details;
try{
Intent newintent = getIntent();
final String itemname = newintent.getStringExtra("itemname");
final String itemprice = newintent.getStringExtra("itemprice");
final String itemquantity = newintent.getStringExtra("itemquantity");
final double totalprice = newintent.getDoubleExtra("totalprice", 0.0);
String totprice=String.valueOf(totalprice);
// ArrayList <String> itemnames=new ArrayList<String>();
listtest.add(itemname);
Log.e("listtest",listtest+"");
final int imagehandler=newintent.getIntExtra("image", 0);
Log.e("image handler",imagehandler+"");
for(int i = 0; i< listtest.size(); i++)
{
details = new CartItems(itemname,itemprice,itemquantity,totprice,imagehandler);
}
}
catch(Exception e){
e.printStackTrace();
}
return details;
}
2) after getting this value, just add it to your arraylist. like this:
CartItems item = SetAdapterList();
detailsList.add(item);
Now, when you populate your listView, detailsList will be having all previously selected items too. Just clear detailsList when you want to reset.
1) Add new items to your detailsList.
2) Call notifyDataSetChanged() for adapter.

Activity reloads the whole data from server again when coming back from an other activity in Android

Basically, I'm working on a app which has a tab-activity including 4 tabs and also I'm using the actvityGroup to manage the activities and backKey pressed() method.
When my app first starts it sends a request to server and shows the progress bar (using AsyncTask) as shown in below image.
After this, my complete UI appears as
it loads new actvity on click event of button "GO" (code is given below)
btnGo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent bookSearchResultActivityIntent = new Intent();
bookSearchResultActivityIntent
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
bookSearchResultActivityIntent.setClass(getParent(),
BookSearchResultActivity.class);
bookSearchResultActivityIntent.putExtra("LANG", language);
bookSearchResultActivityIntent.putExtra("SEARCH_KEYWORDS",
edTxt_SearchField.getText().toString());
MyActivityGroup activityStack = (MyActivityGroup) getParent();
activityStack.push("BooksSearchActivity",
bookSearchResultActivityIntent);
also here is my ActivtyGroup.java code
public class MyActivityGroup extends ActivityGroup {
private Stack<String> stack;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (stack == null) {
stack = new Stack<String>();
}
push("1stStackActivity", new Intent(this, Home.class));
}
#Override
public void finishFromChild(Activity child) {
pop();
}
#Override
public void onBackPressed() {
pop();
}
public void push(String id, Intent intent) {
Window window = getLocalActivityManager().startActivity(id,
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
if (window != null) {
stack.push(id);
setContentView(window.getDecorView());
}
}
public void pop() {
if (stack.size() == 1) {
finish();
}
LocalActivityManager manager = getLocalActivityManager();
manager.destroyActivity(stack.pop(), true);
if (stack.size() > 0) {
Intent lastIntent = manager.getActivity(stack.peek()).getIntent()
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Window newWindow = manager.startActivity(stack.peek(), lastIntent);
setContentView(newWindow.getDecorView());
}
}
}
ok now my question is that when i press the backKey(); it should come to the previous actvity.
Yes it comes to the previous activity but it send request to the server again and shows the progress bar again and loads until the server sends response. it wastes my time.
I only want to load the HomeTab just once (when i play the app). not again and again
I am also adding the
setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
while starting the activity
also added following code in menifest.xml file
android:configChanges="keyboard|keyboardHidden|orientation"
but not working yet.
and here is the code of my Home tab(which sends the request to server in onCreate method)
public class Home extends Activity {
/** Called when the activity is first created. */
static final String URL = "http://www.shiaislamiclibrary.com/requesthandler.ashx";
static final String KEY_ITEM = "Book"; // parent node
static final String KEY_BOOKAUTHOR = "BookAuthor";
static final String KEY_BOOKDATEPUBLISHED = "DatePublished";
static final String KEY_BOOKTITLE = "BookTitle";
static final String KEY_BOOKCODE = "BookCode";
static final String KEY_BOOKIMAGE = "BookImage";
String searchLang;
String searchKeywords;
LayoutInflater inflater = null;
ArrayList<String> BookTitle = new ArrayList<String>();
ArrayList<String> BookCoverPhotos = new ArrayList<String>();
ArrayList<String> BookAuther = new ArrayList<String>();
ArrayList<String> BookPublishDate = new ArrayList<String>();
ArrayList<String> ImageByte = new ArrayList<String>();
ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
Context ctx = this;
Activity act = this;
Context context = Home.this;
URL bookImageURL = null;
Bitmap bitMapImage = null;
Button btnGo;
Spinner spnrLanguage;
Spinner spnrBrowseBy;
String language;
EditText edTxt_SearchField;
GridView gridView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.home_activity);
View viewToLoad = LayoutInflater.from(this.getParent()).inflate(
R.layout.home_activity, null);
this.setContentView(viewToLoad);
gridView = (GridView) findViewById(R.id.gridview);
spnrLanguage = (Spinner) findViewById(R.id.spnrLanguage);
spnrBrowseBy = (Spinner) findViewById(R.id.spnrBrowseBy);
edTxt_SearchField = (EditText) findViewById(R.id.EditTxt_Search);
btnGo = (Button) findViewById(R.id.btn_GO);
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// checking for availbe internet Connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
new UIThread().execute(URL, "Imam Ali");
}
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
Toast.makeText(context, BookTitle.get(pos), Toast.LENGTH_SHORT)
.show();
Intent bookSearchResultActivityIntent = new Intent();
bookSearchResultActivityIntent.setClass(getParent(),
BookOverView.class);
bookSearchResultActivityIntent.putExtra("BITMAP",
bitmapArray.get(pos));
bookSearchResultActivityIntent.putExtra("BOOK_TITLE",
BookTitle.get(pos));
bookSearchResultActivityIntent.putExtra("BOOK_AUTHOR",
BookAuther.get(pos));
bookSearchResultActivityIntent.putExtra("BOOK_PUBLISH_DATE",
BookPublishDate.get(pos));
MyActivityGroup activityStack = (MyActivityGroup) getParent();
activityStack.push("BookOverViewActivity",
bookSearchResultActivityIntent);
}
});
// //////////////////// Spinners handler/////////////////////////
ArrayAdapter<String> adapterLanguage = new ArrayAdapter<String>(
context, android.R.layout.simple_spinner_item, getResources()
.getStringArray(R.array.spnr_language_array));
ArrayAdapter<String> adapterBrowseBy = new ArrayAdapter<String>(
context, android.R.layout.simple_spinner_item, getResources()
.getStringArray(R.array.spnr_browse_array));
spnrLanguage.setAdapter(adapterLanguage);
spnrBrowseBy.setAdapter(adapterBrowseBy);
spnrLanguage.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
Toast.makeText(getParent(),
spnrLanguage.getItemAtPosition(pos) + "",
Toast.LENGTH_SHORT).show();
language = spnrLanguage.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
spnrBrowseBy.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int pos,
long arg3) {
Toast.makeText(context,
spnrBrowseBy.getItemAtPosition(pos) + "",
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
// ////////////////////Search Button Handler/////////////////
btnGo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!edTxt_SearchField.getText().toString().equals("")) {
Intent bookSearchResultActivityIntent = new Intent();
bookSearchResultActivityIntent
.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
bookSearchResultActivityIntent.setClass(getParent(),
BookSearchResultActivity.class);
bookSearchResultActivityIntent.putExtra("LANG", language);
bookSearchResultActivityIntent.putExtra("SEARCH_KEYWORDS",
edTxt_SearchField.getText().toString());
MyActivityGroup activityStack = (MyActivityGroup) getParent();
activityStack.push("BooksSearchActivity",
bookSearchResultActivityIntent);
} else {
Toast.makeText(context, "Search Field Empty",
Toast.LENGTH_SHORT).show();
}
}
});
}
private class UIThread extends AsyncTask<String, Integer, String> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = ProgressDialog.show(getParent(),
"Acumlating Books from server...",
"This may Take a few seconds.\nPlease Wait...");
}
#Override
protected String doInBackground(String... params) {
String URL = params[0];
String searchKeywords = params[1];
XMLParser parser = new XMLParser();
String XMLString = parser.getXmlFromUrl(URL, searchKeywords,
searchLang);
// Log.i("XML Response", XMLString);
Document doc = parser.getDomElement(XMLString);
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
Element e = (Element) nl.item(i);
BookTitle.add(parser.getValue(e, KEY_BOOKTITLE));
BookCoverPhotos.add("http://shiaislamicbooks.com/books_Snaps/"
+ parser.getValue(e, KEY_BOOKCODE) + "/1_thumb.jpg");
BookAuther.add(parser.getValue(e, KEY_BOOKAUTHOR));
BookPublishDate.add(parser.getValue(e, KEY_BOOKDATEPUBLISHED));
Log.i("URLs", BookCoverPhotos.toString());
}
for (int i = 0; i < BookAuther.size(); i++) {
try {
bookImageURL = new URL(BookCoverPhotos.get(i));
} catch (MalformedURLException e) {
e.printStackTrace();
Log.i("URL", "ERROR at image position" + i + "");
}
try {
bitMapImage = BitmapFactory.decodeStream(bookImageURL
.openConnection().getInputStream());
bitmapArray.add(bitMapImage);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("BITMAP", "ERROR" + i);
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
ImageAdapter adapter = new ImageAdapter(getBaseContext(), act);
gridView.setAdapter(adapter);
}
}
public class ImageAdapter extends BaseAdapter {
public ImageAdapter(Context c) {
context = c;
}
// ---returns the number of images---
public int getCount() {
// return imageIDs.length;
return bitmapArray.size();
// return 6;
}
public ImageAdapter(Context ctx, Activity act) {
inflater = (LayoutInflater) act
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// ---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// ---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent) {
// ImageView bmImage;
final ViewHolder holder;
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.grid_style, parent, false);
holder = new ViewHolder();
holder.txt_BooksTitle = (TextView) vi
.findViewById(R.id.txt_BookTitle);
holder.img_BookCoverPhoto = (ImageView) vi
.findViewById(R.id.imgBookCover);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
holder.txt_BooksTitle.setText(BookTitle.get(position) + "");
holder.img_BookCoverPhoto.setImageBitmap(bitmapArray.get(position));
return vi;
}
}
class ViewHolder {
TextView txt_BooksTitle;
ImageView img_BookCoverPhoto;
}
}
please have a look on my activity group class and tell what should i do.
thanks in advance
When loading your data in the Home Tab activity, put it inside some static arrays.
ArrayList<String> BookTitle = new ArrayList<String>();
ArrayList<String> BookCoverPhotos = new ArrayList<String>();
ArrayList<String> BookAuther = new ArrayList<String>();
ArrayList<String> BookPublishDate = new ArrayList<String>();
ArrayList<String> ImageByte = new ArrayList<String>();
ArrayList<Bitmap> bitmapArray = new ArrayList<Bitmap>();
From a quick glimpse on the code, make them static ArrayList<...> ... = null; and check inside the onCreate() method:
if(BookTitle == null)
{
//needs init
BookTitle = new ArrayList<String>();
//perform connect to server and parse response.
}
When the application activity home tab is stopped then restarted, the data will be in memory already and it will skip the if clause keeping the old data for re-use.
Make sure you will clear the static variables when you really want to kill the app - on a quit button click, call a static method to init them to null again, or if you want them to be valid for let's say 12 hours, memorize the timestamp in a static variable and each time you kill/pause the main activity perform a check on it (wheather is null or has a date, if it has a date, check if 12 hours have passed, if yes, clear the static variable contents)
This is the quick and easy way. Another way is to store them in the application database if you don't want to deal with static variables.
There are a lot of options, the point is you kinda have to mark them as "global persistent" data with static, or store them in a databse / file etc.

I want to let user add multiple items by action sequence

I am making an app in which I am fetching data using JSON into ListView, and allowing user to view selected item in another form, in singleMenuItem form.
I have placed a button namely - Add to Cart. Whenever users will click on the Add to Cart button, the selected item needs to show in the View Cart form. The same process will be repeated for each item which is added to the cart.
I just want to show each Item's Title and Cost, for those I am fetching into the SingleMenuItem form using Intent from ListView Form and now I want to show in View Cart Form like:- add multiple items by action sequence, the problem is I don't know how to update View Cart form every time whenever user click on Add to Cart Button.
Catalogue(List View Activity) Code:-
public class Catalogue extends Activity{
static String URL = "http:/--------/and/menu.json";
static String KEY_CATEGORY = "item";
static final String KEY_TITLE = "title";
static final String KEY_DESCRIPTION = "description";
static final String KEY_COST = "cost";
static final String KEY_THUMB_URL = "imageUri";
ListView list;
LazyAdapter adapter;
/** Called when the activity is first created. */
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<HashMap<String, String>> itemsList = new ArrayList<HashMap<String, String>>();
list=(ListView)findViewById(R.id.listView1);
adapter=new LazyAdapter(this, itemsList);
list.setAdapter(adapter);
Intent in = getIntent();
KEY_CATEGORY = in.getStringExtra("category");
try{
JSONArray jsonArray = json.getJSONArray(KEY_CATEGORY);
for(int i=0;i < jsonArray.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonObject = jsonArray.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put(KEY_TITLE, jsonObject.getString(KEY_TITLE));
map.put(KEY_DESCRIPTION, jsonObject.getString(KEY_DESCRIPTION));
map.put(KEY_COST, jsonObject.getString(KEY_COST));
map.put(KEY_THUMB_URL, jsonObject.getString(KEY_THUMB_URL));
itemsList.add(map);
}
return itemsList;
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
return null;
}
#Override
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
list=(ListView)findViewById(R.id.listView1);
adapter=new LazyAdapter(Catalogue.this, itemsList);
list.setAdapter(adapter);
this.progressDialog.dismiss();
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
HashMap<String, String> map = itemsList.get(position);
Intent in = new Intent(Catalogue.this, SingleMenuItem.class);
in.putExtra(KEY_TITLE, map.get(KEY_TITLE));
in.putExtra(KEY_DESCRIPTION, map.get(KEY_DESCRIPTION));
in.putExtra(KEY_THUMB_URL, map.get(KEY_THUMB_URL));
in.putExtra(KEY_COST, map.get(KEY_COST));
startActivity(in);
}
});
ImageButton viewShoppingCart = (ImageButton) findViewById(R.id.ButtonViewCart);
viewShoppingCart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent in = new Intent
(Catalogue.this, FinalOrder.class);
startActivity(in);
}
});
} }}
SingleMenuItem Activity Code
public class SingleMenuItem extends Activity{
static final String KEY_TITLE = "title";
static final String KEY_COST = "cost";
static final String KEY_THUMB_URL = "imageUri";
private EditText edit_qty_code;
private TextView txt_total;
private TextView text_cost_code;
private double itemamount = 0;
private double itemquantity = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.single);
Intent in = getIntent();
String title = in.getStringExtra(KEY_TITLE);
String thumb_url = in.getStringExtra(KEY_THUMB_URL);
final String cost = in.getStringExtra(KEY_COST);
ImageLoader imageLoader = new ImageLoader(getApplicationContext());
ImageView imgv = (ImageView) findViewById(R.id.single_thumb);
TextView txttitle = (TextView) findViewById(R.id.single_title);
TextView txtcost = (TextView) findViewById(R.id.single_cost);
TextView txtheader = (TextView) findViewById(R.id.actionbar);
txttitle.setText(title);
txtheader.setText(title);
txtcost.setText(cost);
imageLoader.DisplayImage(thumb_url, imgv);
ImageButton addToCartButton = (ImageButton) findViewById(R.id.img_add);
addToCartButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent in = new Intent
(SingleMenuItem.this, FinalOrder.class);
in.putExtra(KEY_TITLE, getIntent().getStringExtra(KEY_TITLE));
in.putExtra(KEY_COST, getIntent().getStringExtra(KEY_COST));
startActivity(in);
// Close the activity
finish();
}
});
}}
ViewCart Activity Code:-
public class FinalOrder extends Activity
{
static final String KEY_TITLE = "title";
static final String KEY_COST = "cost";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
Intent in = getIntent();
String title1 = in.getStringExtra(KEY_TITLE);
String cost1 = in.getStringExtra(KEY_COST);
TextView txttitle1 = (TextView) findViewById(R.id.item_name);
TextView txtcost1 = (TextView) findViewById(R.id.item_cost);
txttitle1.setText(title1);
txtcost1.setText(cost1);
}
}
To get the View Cart to update, you need to store the data centrally. Best to use an SQLite database. Then you can update this database when a user adds to the cart, then when viewing the cart, you can read from the database.

pass value from first activity to fourth activity in android

Hi this is my singlemenuitemactivity:
public class SingleMenuItemActivity extends ExpandableListActivity {
Button btninsert;
String selectedItem;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.particular);
Button btninsert = (Button) findViewById(R.id.btn_insert);
btninsert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(), InsertionExample.class);
String s1= getIntent().getStringExtra("orderid");
i.putExtra(KEY_NAME, orderid);
startActivity(i);
}
});
// Construct Expandable List
final String NAME1 = "payment_method1";
final String NAME = "payment_method";
final String TOTAL = "total";
final String TOTAL1 = "total1";
final String ID = "orderid";
final String ID1 = "orderid1";
final String IMAGE = "image";
final String FNAME1 = "firstname1";
final String FNAME = "firstname";
final String LNAME1 = "lastname1";
final String LNAME = "lastname";
final LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final ArrayList<HashMap<String, String>> headerData = new ArrayList<HashMap<String, String>>();
final HashMap<String, String> group1 = new HashMap<String, String>();
group1.put(NAME, "OrderInfo");
headerData.add( group1 );
final HashMap<String, String> group2 = new HashMap<String, String>();
group2.put(NAME, "CustomerInfo");
headerData.add( group2);
// final HashMap<String, String> group3 = new HashMap<String, String>();
// group3.put(NAME, "Group 3");
// headerData.add( group3);
final ArrayList<ArrayList<HashMap<String, Object>>> childData = new ArrayList<ArrayList<HashMap<String, Object>>>();
final ArrayList<HashMap<String, Object>> group1data = new ArrayList<HashMap<String, Object>>();
childData.add(group1data);
final ArrayList<HashMap<String, Object>> group2data = new ArrayList<HashMap<String, Object>>();
childData.add(group2data);
// final ArrayList<HashMap<String, Object>> group3data = new ArrayList<HashMap<String, Object>>();
// childData.add(group3data);
// Set up some sample data in both groups
for( int i=0; i<1; ++i) {
final HashMap<String, Object> map = new HashMap<String,Object>();
String s= getIntent().getStringExtra("payment_method");
String s1= getIntent().getStringExtra("total");
String selectedItem= getIntent().getStringExtra("selectedItem");
String s5= getIntent().getStringExtra("orderid");
map.put(NAME1, "Payment_method:");
map.put(NAME, s );
map.put(TOTAL1, "Total:");
map.put(TOTAL, s1);
map.put(ID1, "Total:");
map.put(ID, s5);
group1data.add(map);
// map.put(IMAGE, getResources().getDrawable((i%3==0? R.drawable.color_green : R.drawable.color_red)));
// ( i%2==0 ? group1data : group2data ).add(map);
}
final HashMap<String, Object> map = new HashMap<String,Object>();
String s1= getIntent().getStringExtra("firstname");
String s2= getIntent().getStringExtra("lastname");
map.put(FNAME, s1);
map.put(FNAME1, "Firstname:");
map.put(LNAME, s2);
map.put(LNAME1, "Lastname:");
// map.put(IMAGE, getResources().getDrawable(R.drawable.color_yellow));
group2data.add(map);
setListAdapter( new SimpleExpandableListAdapter(
this,
headerData,
R.layout.group_row,
new String[] { NAME, FNAME }, // the names of the data
new int[] { R.id.order }, // the text field to populate with the field data
childData,
0,
null,
new int[] {}
) {
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
final View v = super.getChildView(groupPosition, childPosition, isLastChild, convertView, parent);
// Spinner spinner = (Spinner) findViewById(R.id.spnMusketeers);
// Populate your custom view here
((TextView)v.findViewById(R.id.payment_method1)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(NAME1) );
((TextView)v.findViewById(R.id.payment_method)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(NAME) );
((TextView)v.findViewById(R.id.firstname)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(FNAME) );
((TextView)v.findViewById(R.id.firstname1)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(FNAME1) );
((TextView)v.findViewById(R.id.total1)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(TOTAL1) );
((TextView)v.findViewById(R.id.total)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(TOTAL) );
((TextView)v.findViewById(R.id.lastname)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(LNAME) );
((TextView)v.findViewById(R.id.lastname1)).setText( (String) ((Map<String,Object>)getChild(groupPosition, childPosition)).get(LNAME1) );
return v;
}
#Override
public View newChildView(boolean isLastChild, ViewGroup parent) {
return layoutInflater.inflate(R.layout.expandable_list_item_with_image,null, false);
}
}
);
ExpandableListView list = (ExpandableListView) findViewById(android.R.id.list);
list.setOnChildClickListener(new OnChildClickListener(){
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
System.out.println("Group:"+groupPosition+", Child: "+childPosition);
return true;
}
});
}}
this is my insertionexample.java
public class InsertionExample extends Activity {
private final String NAMESPACE = "http://xcart.com";
private final String URL = "http://192.168.1.168:8089/XcartLogin/services/update?wsdl";
private final String SOAP_ACTION = "http://xcart.com/insertData";
private final String METHOD_NAME = "insertData";
Button btninsert;
String selectedItem;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.change_status);
//get reference to the spinner from the XML layout
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
btninsert = (Button)findViewById(R.id.btn_insert1);
btninsert.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText Orderid = (EditText) findViewById(R.id.orderid);
String orderid = Orderid.getText().toString();
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText("Welcome ,"+getIntent().getExtras().getString("orderid"));
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo unameProp =new PropertyInfo();
unameProp.setName("Status");//Define the variable name in the web service method
unameProp.setValue(selectedItem);//Define value for fname variable
unameProp.setType(String.class);//Define the type of the variable
request.addProperty(unameProp);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try{
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
TextView result = (TextView) findViewById(R.id.textView2);
result.setText(response.toString());
}
catch(Exception e){
}
}
});
//attach the listener to the spinner
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
//Dynamically generate a spinner data
createSpinnerDropDown();
}
//Add animals into spinner dynamically
private void createSpinnerDropDown() {
//get reference to the spinner from the XML layout
Spinner spinner = (Spinner) findViewById(R.id.spinner1);
//Array list of animals to display in the spinner
List<String> list = new ArrayList<String>();
list.add("Q");
list.add("P");
list.add("F");
list.add("I");
list.add("C");
//create an ArrayAdaptar from the String Array
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
//set the view for the Drop down list
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//set the ArrayAdapter to the spinner
spinner.setAdapter(dataAdapter);
//attach the listener to the spinner
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
selectedItem = parent.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
}
here my doubt is the orderid is parsed from xml parsing...the update operation is performed soap calling..now here i have to update the status from orderid...how is to do..this is my update query.
"UPDATE `xcart_orders` set `status` = '"+Status+"' where `orderid` = '"+Orderid+"'"
please help me...how is update status depends upon orderid from xml parsing..how is change my code...how is to do...please help me
Use shared preferences or Application class
Shared preferences example
Application class example
You have 2 ways to do this:
1- Use public static values to store username and password (not recommended)
2- Use sharedPreferences as below:
in your first activity, to save username and password:
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
data.edit().putString("UserName", userName).commit();
data.edit().putString("Password", password).commit();
in the fourth activity to retrieve username and password:
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String userName = data.getString("UserName", "THIS IS DEFAULT VALUE");
String password = data.getString("Password", "THIS IS DEFAULT VALUE");
You can Do this using the Getters and setters methods.
create one class :
public class SelectedAnswer {
public static String uname;
public static String getAnswer() {
return uname;
}
public static void setAnswer(String answer) {
uname = answer;
}
}
Then set the username value into your first activty.
SelectedAnswer.setAnswer(uName);
and get the value into fourth activity.
String answer = SelectedAnswer.getAnswer();
you can also use setter getter class to set data and access data anywhere in application by just creating object for that class. in your case this might be useful.
Either use some static variables to store this or use shared preference. If you have more than one activty where you need to transfer data, its better to use a static dictionary which will help you to save activity specific data.
For Example :
We can create a simple data cacher class for this :
public class MyActivityDataCacher {
private static HashMap<String, String> mDataCacher;
static{
mDataCacher=new HashMap<String, String>();
}
public static void putDataFor(String className, String data) {
mDataCacher.put(className, data);
}
public static String getDataFor(String className) {
if (mDataCacher.containsKey(className)) {
return mDataCacher.get(className);
} else {
return "";
}
}
}
For storing Data for a particular Activity (Say MainActivity) :
MyActivityDataCacher.putDataFor(MainActivity.class.getName(), "Test Data");
For Retrieving the data stored :
MyActivityDataCacher.getDataFor(MainActivity.class.getName());
If you have data which must be accessed from different parts of your application you can use Singleton pattern as data holder.

Categories

Resources