2017-08-11 97 views
-1

我有第二個活動處理所有用戶輸入,另一個活動處理來自第二個活動的所有數據。我想要做的是從活動中調用一個類「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」類到第二個活動,以便不再進行數據傳遞。

+0

你在做什麼/避免在這裏? –

+0

這是很多代碼。考慮創建一個[最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 –

+0

「意圖」是從一種活動轉移到另一種活動的正確方法。大多數「經典」的java方式不能保證,對象可以交換等等... –

回答

0

正如其他朋友提到的Intent是在活動之間傳遞數據的正確和好方法。但是如果你想避免編寫這麼多的代碼來傳輸數據,我建議創建一個純java類(或java bean)並定義該類中所有需要的字段(注意:該類應該實現java.io.Serializable接口)。現在,您可以在活動之間傳輸此類的實例。

0

我不認爲在活動之間傳遞數據比intents更好。 你可能需要的是封裝額外的傳遞。您可以通過在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; 

} 

然後在調用者類,你通過makeing該函數的靜態調用做出的意圖,並且將值作爲參數

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

然而,在你的情況,你應該做出更明智傳遞數據的方式不如字符串數組。

+0

有沒有什麼辦法可以直接從ViolatorDetail.class輸入數據到recyclerview?因此,MainActivity的recyclerview只會直接顯示其內容。沒有從MainActivity存儲到recyclerview中? – randolfrojo11

+0

我看到你的唯一方法可以達到你所要求的是通過在一個活動中進行永恆化,隱藏和顯示視圖。 但它是一個壞的預兆,我會建議反對它。 從長遠來看,通常更簡單的解決方案會變得更加複雜。 所以這不是「我可以」而是「我應該」的問題...... – Gotiasits

0

如果你不想與Intent傳遞活動之間的數據,你可以通過在file寫某些數據做到這一點,當你需要它只是從它讀......我做到了這樣,我仍然很高興我這樣做,這很簡單,相對較快,你只需要關心一下IOExceptions

相關問題