将班级称为另一项活动

时间:2017-08-11 11:06:58

标签: java android android-activity

我有第二个活动处理所有用户输入,另一个活动处理来自第二个活动的所有数据。我想要做的是从活动中调用类“SubmitName”到第二个活动,这样我就不再需要将值从第二个活动传递给主活动了。这是代码..

MainActivity(“SubmitName”类所在的位置,并传递值。)

public class MainActivity extends AppCompatActivity  {
RecyclerView recyclerView;
TextView Name;
String lastname;
String licensenumber;
String mviolation;
String maplace;
String maddress;
String phonenumber;
String officername;
String contactnumber;
String datetime;
RecyclerView.LayoutManager layoutManager;
RecyclerAdapter adapter;
ArrayList<Violator> arrayList = new ArrayList<>();
BroadcastReceiver broadcastReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);




    Button addBtn = (Button)findViewById(R.id.btnAdd);

    addBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, FragActivity.class);
            startActivity(intent);
        }
    });

    recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
    Name = (TextView) findViewById(R.id.tvName);
    Intent intent = getIntent();
    String str = intent.getStringExtra("firstname");
    lastname = intent.getStringExtra("lastname");
    licensenumber = intent.getStringExtra("licensenumber");
    mviolation = intent.getStringExtra("violation");
    maplace = intent.getStringExtra("arrestplace");
    maddress = intent.getStringExtra("address");
    phonenumber = intent.getStringExtra("phonenumber");
    contactnumber = intent.getStringExtra("contactnumber");
    officername = intent.getStringExtra("officername");
    datetime = intent.getStringExtra("datetime");
    Name.setText(str);
    layoutManager = new LinearLayoutManager(this);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setHasFixedSize(true);
    adapter = new RecyclerAdapter(arrayList);
    recyclerView.setAdapter(adapter);
    readFromLocalStorage();
    broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            readFromLocalStorage();

        }
    };
}




@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.nav_bar, menu);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()){
        case R.id.TrafficAd:
            Intent i = new Intent(this, TrafficAdvisory.class);
            this.startActivity(i);
            break;
    }
    return super.onOptionsItemSelected(item);
}

public void submitName(View view)
{

    String name = Name.getText().toString();
    String lname = lastname;
    String lnumber = licensenumber;
    String violation = mviolation;
    String aplace = maplace;
    String address = maddress;
    String pnumber = phonenumber;
    String cnumber = contactnumber;
    String oname = officername;
    String dtime = datetime;
    saveToAppServer(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime);
    Name.setText("");
}

public void readFromLocalStorage()
{
    arrayList.clear();
    DbHelper dbHelper = new DbHelper(this);
    SQLiteDatabase database = dbHelper.getReadableDatabase();

    Cursor cursor = dbHelper.readFromLocalDatabase(database);

    while (cursor.moveToNext())
    {
        String name = cursor.getString(cursor.getColumnIndex(DBContract.NAME));
        String lname = cursor.getString(cursor.getColumnIndex(DBContract.LNAME));
        String lnumber = cursor.getString(cursor.getColumnIndex(DBContract.LNUMBER));
        String violation = cursor.getString(cursor.getColumnIndex(DBContract.VIOLATION));
        String aplace = cursor.getString(cursor.getColumnIndex(DBContract.ARRESTPLACE));
        String address = cursor.getString(cursor.getColumnIndex(DBContract.ADDRESS));
        String pnumber = cursor.getString(cursor.getColumnIndex(DBContract.PNUMBER));
        String cnumber = cursor.getString(cursor.getColumnIndex(DBContract.CNUMBER));
        String oname = cursor.getString(cursor.getColumnIndex(DBContract.ONAME));
        String dtime = cursor.getString(cursor.getColumnIndex(DBContract.DTIME));
        int sync_status = cursor.getInt(cursor.getColumnIndex(DBContract.SYNC_STATUS));
        arrayList.add(new Violator(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,sync_status));


    }

    adapter.notifyDataSetChanged();
    cursor.close();


}

public void saveToAppServer(final String name,final String lname, final String lnumber,final String violation, final  String aplace,final String address, final String pnumber, final String cnumber, final String oname, final String dtime)
{


    if (checkNetworkConnection())
    {
        StringRequest stringRequest = new StringRequest(Request.Method.POST,DBContract.SERVER_URL,
                new Response.Listener<String>(){
                    @Override
                    public void onResponse(String response){
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String Response = jsonObject.getString("response");
                            if(Response.equals("OK"))
                            {
                                saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_OK);
                            }
                            else
                            {
                                saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_FAILED);
                            }

                        } catch (JSONException e){
                            e.printStackTrace();
                        }
                    }
                },new Response.ErrorListener(){
            @Override
            public void onErrorResponse(VolleyError error){

                saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_FAILED);
            }
        })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> params = new HashMap<>();
                params.put("name",name);
                params.put("lname",lname);
                params.put("lnumber",lnumber);
                params.put("violation", violation);
                params.put("aplace", aplace);
                params.put("address",address);
                params.put("pnumber",pnumber);
                params.put("cnumber",cnumber);
                params.put("oname",oname);
                params.put("dtime",dtime);
                return params;
            }
        }
                ;
                MySingleton.getInstance(MainActivity.this).addToRequestQue(stringRequest);
    }
    else
    {
        saveToLocalStorage(name,lname,lnumber,violation,aplace,address,pnumber,cnumber,oname,dtime,DBContract.SYNC_STATUS_FAILED);
    }


}

SecondActivity(处理输入并将数据传递给mainactivity)

public class ViolatorDetail extends AppCompatActivity implements View.OnClickListener{

EditText Name;
Button btnClose;
TextView DTime;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_violator_detail);



    DTime = (TextView)findViewById(R.id.tvDTime);
    final String currentDT = DateFormat.getDateTimeInstance().format(new Date());
    DTime.setText(currentDT);

    btnClose = (Button) findViewById(R.id.btnClose);
    btnClose.setOnClickListener(this);

    Button btnSubmit = (Button)findViewById(R.id.btnSubmit);
    btnSubmit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            EditText Name = (EditText)findViewById(R.id.etfName);
            EditText LName = (EditText)findViewById(R.id.etlName);
            EditText LNumber = (EditText)findViewById(R.id.etlNumber);
            EditText Violation = (EditText)findViewById(R.id.etViolation);
            EditText Arrestplace = (EditText)findViewById(R.id.etaPlace);
            EditText Address = (EditText)findViewById(R.id.etAddress);
            EditText PNumber = (EditText)findViewById(R.id.etpNumber);
            EditText CNumber = (EditText)findViewById(R.id.etcNumber);
            EditText OName = (EditText)findViewById(R.id.etoName);
            String DT = DTime.getText().toString();
            Intent intent = new Intent(ViolatorDetail.this, MainActivity.class);
            intent.putExtra("firstname", Name.getText().toString());
            intent.putExtra("lastname", LName.getText().toString());
            intent.putExtra("licensenumber", LNumber.getText().toString());
            intent.putExtra("violation", Violation.getText().toString());
            intent.putExtra("arrestplace", Arrestplace.getText().toString());
            intent.putExtra("address", Address.getText().toString());
            intent.putExtra("phonenumber", PNumber.getText().toString());
            intent.putExtra("contactnumber", CNumber.getText().toString());
            intent.putExtra("officername", OName.getText().toString());
            intent.putExtra("datetime", DT);
            startActivity(intent);
        }
    });





}

}

我想要做的是将“SUBMITNAME”类调用到第二个活动,这样就不会再进行数据传递了。

3 个答案:

答案 0 :(得分:0)

正如其他朋友提到的Intent是在活动之间传输数据的正确而好的方法。但是如果你想避免编写这么多代码来传输数据,我建议创建一个纯java类(或java bean)并定义该类中所有需要的字段(注意:这个类应该实现java.io.Serializable接口)。现在,您可以在活动之间传输此类的实例。

答案 1 :(得分:0)

我认为在Intents之间传递数据的方式并不比Intent更好。 你可能需要的是封装传递额外的东西。您可以通过在ViolatorDetail类中创建一个静态方法来实现这一点,该方法接受您希望传递的值作为参数,并返回Intent。

public static Intent newIntent(Context packageContext, String ... args){

     Intent intent = new Intent(packageContext, ViolatorDetail.this);
     intent.putExtra(EXTRA_STRING_ARGS, args);
     return intent;

}

然后在调用者类中,通过对该函数进行静态调用来创建一个intent,并将值作为参数传递

Intent intent = ViolatorDetail.newIntent(getActivity(), strings)
startActivity(intent);

但是,在您的情况下,您应该采用更合理的方式传递数据而不是字符串数组。

答案 2 :(得分:0)

如果您不想在具有Intent的活动之间传递数据,您可以通过在file中写入某些数据来完成此操作,当您需要时,只需从中读取...我做了它是这样的,我仍然很高兴我这样做,它很简单,相对较快,你只需要关心IOExceptions