两个活动相互发送数据

时间:2015-05-23 11:36:36

标签: android

两项活动是相互发送数据。

第一个活动有一个自定义列表视图。第二个有一个文本视图和三个按钮来增加和减少一个值。

当我点击第一个活动时,第二个活动会打开。第二个活动会增加文本视图值并单击按钮。数据转到第一个活动。同样的过程。

我的问题是第一项活动中没有显示总值。

如何在第一个活动中显示第二个活动的所有增加和减少值?

第一项活动的代码:

package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;
import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.json.JSONfunctions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;

public class DetaisRESTActivity extends Activity {
    String messagevaluename,valueid,valueid1,valuename,pos;
    public String countString=null;
    String nameofsubmenu;
    public int count=0;
    public  String message=null;
    public  String message1=null;
    JSONObject jsonobject;
    JSONArray jsonarray;
    ListView   listview;
    ArrayList aa;
    public  SharedPreferences.Editor edit;
    public TextView   mTitleTextView;
    public   ImageButton imageButton;
    ListAdapterAddItems adapter;
    public TextView restaurantname = null;
    public TextView ruppees = null;
    ProgressDialog mProgressDialog;
    ArrayList<ListModel> arraylist;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detais_rest);
        ActionBar actionBar = getActionBar();

        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));

        SharedPreferences preferences=getSharedPreferences("temp1", 1);



        //     SharedPreferences.Editor editor = preferences.edit();
        int na=preferences.getInt("COUNTSTRING1",0);
        Log.i("asasassas",""+na);

        LayoutInflater mInflater = LayoutInflater.from(this);

        View mCustomView = mInflater.inflate(R.layout.titlebar, null);
        mTitleTextView = (TextView) mCustomView.findViewById(R.id.textView123456789);

        imageButton = (ImageButton) mCustomView
                .findViewById(R.id.imageButton2);

        imageButton.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(View view) {
                Toast.makeText(getApplicationContext(), "Refresh Clicked!",
                        Toast.LENGTH_LONG).show();

                Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);


                startActivity(i);
            }
        });

        actionBar.setCustomView(mCustomView);
        actionBar.setDisplayShowCustomEnabled(true);
    //    SqliteControllerSqliteController db = new SqliteControllerSqliteController(QuentityActivity.this);
        // Reading all contacts

   /*
        Log.d("Reading: ", "Reading all contacts..");
        List<Contact> contacts = db.getAllContacts();

        for (Contact cn : contacts) {
            String log = "Id: "+cn.getID()+" ,Name: " + cn.getName() + " ,Phone: " +
                    cn.getPhoneNumber();
            // Writing Contacts to log
            Log.d("Name: ", log);
        }

*/
















        Intent intent = getIntent();
        // get the extra value
        valuename = intent.getStringExtra("restaurantmenuname");
        valueid = intent.getStringExtra("restaurantmenunameid");
        valueid1 = intent.getStringExtra("idsrestaurantMenuId5");
        //totalamount = intent.getStringExtra("ruppees");
        Log.i("valueid",valueid);
        Log.i("valuename",valuename);
        Log.i("valueid1",valueid1);
       // Log.i("totalamount",totalamount);

        new DownloadJSON().execute();
    }


    // DownloadJSON AsyncTask
    private class DownloadJSON extends AsyncTask<Void,Void,Void> {

        @Override

        protected void onPreExecute() {
            super.onPreExecute();
            // Create a progressdialog
            mProgressDialog = new ProgressDialog(DetaisRESTActivity.this);
            // Set progressdialog title
            mProgressDialog.setTitle("Android JSON Parse Tutorial");
            // Set progressdialog message
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            // Show progressdialog
            mProgressDialog.show();
            Toast.makeText(DetaisRESTActivity.this, "Successs", Toast.LENGTH_LONG).show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<ListModel>();
            // Retrieve JSON Objects from the given URL address
            //  Log.i("123",value1);
            jsonobject = JSONfunctions.getJSONfromURL("http://firstchoicefood.in/fcfapiphpexpert/phpexpert_restaurantMenuItem.php?r=" + URLEncoder.encode(valuename) + "&resid=" + URLEncoder.encode(valueid1) + "&RestaurantCategoryID=" + URLEncoder.encode(valueid) + "");



            try {

                // Locate the array name in JSON
                jsonarray = jsonobject.getJSONArray("RestaurantMenItems");
                Log.i("1234",""+jsonarray);

                for (int i = 0; i < jsonarray.length(); i++) {

                    jsonobject = jsonarray.getJSONObject(i);


                     ListModel sched = new ListModel();
                    sched.setId(jsonobject.getString("id"));
                    sched.setProductName(jsonobject.getString("RestaurantPizzaItemName"));

                    sched.setPrice(jsonobject.getString("RestaurantPizzaItemPrice"));

                    arraylist.add(sched);


                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            // Locate the listview in listview_main.xml
      listview = (ListView) findViewById(R.id.listViewdetails);

            adapter = new ListAdapterAddItems();

            listview.setAdapter(adapter);
            // Close the progressdialog
            mProgressDialog.dismiss();

            adapter.notifyDataSetChanged();

            listview.setOnItemClickListener(new AdapterView.OnItemClickListener()
            {
                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3)
                {

                    // Get Person "behind" the clicked item
                    ListModel p =(ListModel)listview.getItemAtPosition(position);
                    // Log the fields to check if we got the info we want
                    Log.i("SomeTag",""+p.getId());
                    //String itemvalue=(String)listview.getItemAtPosition(position);
                    Log.i("SomeTag", "Persons name: " + p.getProductName());
                    Log.i("SomeTag", "Ruppees: " + p.getPrice());

                    Toast toast = Toast.makeText(getApplicationContext(),
                            "Item " + (position + 1),
                            Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
                    toast.show();

                       Log.i("postititi",""+position);

                    Intent intent=new Intent(DetaisRESTActivity.this,QuentityActivity.class);
                    intent.putExtra("quentity",countString);
                    intent.putExtra("valueid",valueid);
                    intent.putExtra("valuename",valuename);
                    intent.putExtra("valueid1",valueid1);
                    intent.putExtra("id",p.getId());
                    intent.putExtra("name",p.getProductName());
                    intent.putExtra("price",p.getPrice());
                    startActivityForResult(intent,2);
                   // startActivity(intent);

                }
            });

        }
    }


    // Call Back method  to get the Message form other Activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        // check if the request code is same as what is passed  here it is 2
        if(requestCode==2)
        {

            pos=data.getStringExtra("POSITION");
            message=data.getStringExtra("MESSAGE");
            message1=data.getStringExtra("COUNTSTRING");
            messagevaluename=data.getStringExtra("VALUENAME");
            nameofsubmenu=data.getStringExtra("name");
            Log.i("xxxxxxxxxxx",message);
            Log.i("xxxxxxxxxxx1234",pos);
            Log.i("xxxxxxxxxxx5678count",message1);
            Log.i("messagevaluename",messagevaluename);
            Log.i("submenu",nameofsubmenu);
            //ruppees.setText(message);
            //editor.putInt("count",na);
            //editor.commit();
            //Log.i("asasassasasdsasdasd",""+na);

           //  mTitleTextView.setText(Arrays.toString(message1));
            mTitleTextView.setText(message1);

            imageButton.setOnClickListener(new View.OnClickListener() {


                @Override
                public void onClick(View view) {
                    Toast.makeText(getApplicationContext(), message,
                            Toast.LENGTH_LONG).show();
                    Intent i=new Intent(DetaisRESTActivity.this,TotalPriceActivity.class);
                    i.putExtra("count",message1);

                    i.putExtra("submenu",nameofsubmenu);
                    i.putExtra("ruppees",message);
                    i.putExtra("id",pos);
                    i.putExtra("messagevaluename",messagevaluename);
                    startActivity(i);

                }
            });


        }
    }

    //==========================
    class ListAdapterAddItems extends ArrayAdapter<ListModel>
    {
        ListAdapterAddItems(){
            super(DetaisRESTActivity.this,android.R.layout.simple_list_item_1,arraylist);
            //imageLoader = new ImageLoader(MainActivity.this);
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;
            if(convertView == null){
                LayoutInflater inflater = getLayoutInflater();
                convertView = inflater.inflate(R.layout.cartlistitem, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            }else{
                holder = (ViewHolder)convertView.getTag();
            }
            holder.populateFrom(arraylist.get(position));

          //  arraylist.get(position).getPrice();
            return convertView;
        }
    }

    class ViewHolder {



        ViewHolder(View row) {
            restaurantname = (TextView) row.findViewById(R.id.rastaurantnamedetailsrestaurant);
            ruppees = (TextView) row.findViewById(R.id.rastaurantcuisinedetalsrestaurant);

        }

        // Notice we have to change our populateFrom() to take an argument of type "Person"
        void populateFrom(ListModel r) {
            restaurantname.setText(r.getProductName());
            ruppees.setText(r.getPrice());

        }


    }














        //=============================================================






    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_detais_rest, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.


        return super.onOptionsItemSelected(item);
    }
public void OnPause(){
    super.onPause();


}
}

第二项活动的代码:

package com.firstchoicefood.phpexpertgroup.firstchoicefoodin;

import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.CARTBean;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.bean.ListModel;
import com.firstchoicefood.phpexpertgroup.firstchoicefoodin.database.SqliteController;


public class QuentityActivity extends Activity {
String value=null;
    public String TotAmt=null;
    String[] cccc;
    ImageButton positive,negative;
    String position;
    static int count = 1;
    int tot_amt = 0;
    public  String countString=null;
    String name,price;
    String valueid,valueid1,valuename;

    public TextView ruppees,submenuname,totalruppees,quantity,addtocart;
    SharedPreferences preferences;
    SharedPreferences.Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_quentity);
        ActionBar actionBar = getActionBar();

        // Enabling Up / Back navigation
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ff0000")));
        preferences = getSharedPreferences("temp1",1);
      editor = preferences.edit();

        Intent intent = getIntent();
        // get the extra value
        value = intent.getStringExtra("quentity");
        valuename = intent.getStringExtra("valuename");
        valueid = intent.getStringExtra("valueid");
        valueid1 = intent.getStringExtra("valueid1");
        name=intent.getStringExtra("name");
        price=intent.getStringExtra("price");
        position=intent.getStringExtra("id");

        quantity=(TextView)findViewById(R.id.rastaurantcuisinedetalsrestaurantquantity);
        totalruppees=(TextView)findViewById(R.id.rastaurantnamequentitytotal1);
        submenuname=(TextView)findViewById(R.id.rastaurantnamesubmenuquentity);
        ruppees=(TextView)findViewById(R.id.rastaurantnamequentity1);
        positive=(ImageButton)findViewById(R.id.imageButtonpositive);
        negative=(ImageButton)findViewById(R.id.imageButtonnegative);
        addtocart=(TextView)findViewById(R.id.textViewaddtocart);
        buttonclick();
        addtocart();


        submenuname.setText(name);
        ruppees.setText(price);
        totalruppees.setText(price);
        // new DownloadJSON().execute();
    }


    public void buttonclick(){
        positive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {





                String totalAmtString = ruppees.getText().toString();
                int totAmount = Integer.parseInt(totalAmtString);
                //count = Integer.parseInt(getString);
                count++;

                editor.putInt("COUNTSTRING1", count);
                editor.commit();
                editor.clear();
                Log.i("sunder sharma",""+count);
                countString= String.valueOf(count);
                tot_amt = totAmount * count;

                TotAmt = String.valueOf(tot_amt);

                totalruppees.setText(TotAmt);
                quantity.setText(countString);

           }
        });


        negative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String totalAmtString = ruppees.getText().toString();
                int totAmount = Integer.parseInt(totalAmtString);

                if (count > 1)
                    count--;
                editor.putInt("COUNTSTRING1", count);
                editor.commit();
                countString = String.valueOf(count);

                tot_amt = totAmount * count;

                TotAmt = String.valueOf(tot_amt);

                totalruppees.setText(TotAmt);
                quantity.setText(countString);

            }
        });

    }
    public void addtocart(){
        addtocart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

          /*      Log.i("valueid",valueid);
                Log.i("valuename",valuename);
                Log.i("valueid1",valueid1);
                Log.i("name",name);
                Log.i("price",price);
                Log.i("id1",position);
                SqliteController db = new SqliteController(QuentityActivity.this);
                db.insertStudent(new CARTBean(position,name,price,countString,TotAmt));


*/








                Intent intent=new Intent();
                intent.putExtra("MESSAGE",TotAmt);
                intent.putExtra("POSITION",position);
                intent.putExtra("COUNTSTRING",countString);

                intent.putExtra("VALUENAME",valuename);
                intent.putExtra("name",name);
                setResult(2,intent);
                finish();//finishing activity

            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_quentity, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

1 个答案:

答案 0 :(得分:0)

从第二项活动中收集数据并将其置于下方。然后您将收到第一项活动。

Intent myIntent = new Intent(secondActivity.this, firstActivity.class);
myIntent.putExtra("COUNTSTRING", CountString);    //add data
startActivity(myIntent);