2015-02-10 165 views
0

在我的應用程序中它有三個片段。每個片段都有付款按鈕,只要我們點擊付款按鈕,一個服務就會打電話。所以對於我在非活動類中編寫服務的所有片段。該服務需要來自每個片段的兩個變量。所以我把這些變量發送到非活動類如下:如何在android中從非活動類移動到活動類?

fragment1: 


paymentbtn.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
      Payment payment = new Payment(getActivity(),Mobilenumber,amount); 
} 

    fragment2: 


    paymentbtn.setOnClickListener(new View.OnClickListener() { 
        @Override 
        public void onClick(View v) { 
        Payment payment = new Payment(getActivity(),Mobilenumber,amount); 
     } 

fragment3: 


paymentbtn.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
      Payment payment = new Payment(getActivity(),Mobilenumber,amount); 
} 




payment.java: 

    public class Payment { 
     JSONArray OrderItem; 
     String mobNumber, amount; 
     Context context; 
     String payjson, jsontopayment; 
     static Payment INSTANCE; 

     public Payment(Context context, String mobNumber, String amount) { 
      db = new DatabaseHandler(context); 
      INSTANCE = this; 

      this.mobNumber = mobNumber; 
      this.amount = amount; 

      new GetPayment().execute(WebUrl.RechargeServiceURL + "AddRecharge"); 
     } 

     public class GetPayment extends AsyncTask<String, Void, String> { 
      /*String mJourneyDate; 
      public GetData(String pJourneyDate) { 
       this.mJourneyDate = pJourneyDate; 
      }*/ 
      @Override 
      protected void onPreExecute() { 
       super.onPreExecute(); 
      } 

      @Override 
      protected String doInBackground(String... params) { 
       String response; 

       try { 
        HttpClient httpclient = new DefaultHttpClient(); 
        HttpPost httppost = new HttpPost(params[0]); 
        List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(7); 
        nameValuePair.add(new BasicNameValuePair("UserUniqueID", "823166FC-83B5-4D7A-816BF81B6B0A5177")); 
        nameValuePair.add(new BasicNameValuePair("AccountNumber", mobNumber)); 
        nameValuePair.add(new BasicNameValuePair("RCTypeID", rctypeid)); 
        nameValuePair.add(new BasicNameValuePair("OperatorID", opid)); 
        nameValuePair.add(new BasicNameValuePair("ServiceTypeID", srid)); 
        nameValuePair.add(new BasicNameValuePair("CircleID", crid)); 
        nameValuePair.add(new BasicNameValuePair("Amount", amount)); 
        nameValuePair.add(new BasicNameValuePair("DeviceID", "yeryer")); 

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePair)); 
        HttpResponse responce = httpclient.execute(httppost); 

        HttpEntity httpEntity = responce.getEntity(); 

        response = EntityUtils.toString(httpEntity); 

        // Log.d("response is", response); 
        return response; 
       } catch (Exception ex) { 
        ex.printStackTrace(); 
       } 

       return null; 
      } 

      @Override 
      protected void onPostExecute(String result) { 
       String Status; 

       super.onPostExecute(result); 
       //Log.v("TAG_RESULT",""+result); 

       if (result != null) { 
        try { 
         ////here i want to send the result to activty class 
         //result have json response`enter code here` 
        } catch (Exception e) { 
         e.printStackTrace(); 
        } 
       } else { 
        Toast.makeText(context, "something went wrong", Toast.LENGTH_LONG).show(); 
       } 
      } 
     } 

     public String getJson() { 
      payjson = OrderItem.toString(); 
      Log.v("test", "test"); 
      return payjson; 
     } 
    } 

paymentActivty.java: 

    public class Payment_Actiivity extends Activity { 
     Payment pay; 
     String json; 
     String str; 

     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_payment); 
     // i need the json response in this class 
     } 
    } 


i got the json response in non activty class. now i need to add this json data to another activity(payment_activity). so how i get my json response data to payment_activty. now my aim is whenever i click payment button in every fragment, it need to go payment_activity. please help me out. 
+0

[安卓自定義事件監聽器(http://stackoverflow.com/questions/22881661/android-custom-event-listener)是解決問題 – 2015-02-10 08:34:39

+0

對不起有用。我沒有得到。我新來java和andorid。請給予一些澄清 – Kartiki 2015-02-10 08:39:45

回答

0

您可以使用廣播來實現你想要的。以下是代碼,請嘗試:

將此方法添加到要發送結果的位置。

private void sendResult(String result){ 
    Intent intent = new Intent("yourpackage.result"); 
    intent.putExtra("my_result", result); 
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent); 
} 

將以下代碼添加到您的活動中。

private BroadcastReceiver mReceiver; 

// call this method in onCreate() 
private void registerResultReceiver(){ 
    mReceiver = new BroadcastReceiver(){ 

     @Override 
     public void onReceive(Context context, Intent intent) { 
      // here your get the result 
      String result = intent.getStringExtra("my_result"); 
     } 

    }; 
    IntentFilter filter = new IntentFilter("yourpackage.result"); 
    LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, filter); 
} 

將此行添加到Activity的onDestroy()方法中以註銷接收者。

LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver); 
+0

對不起,leog,yourpakage.result的意思是,,,,,? – Kartiki 2015-02-10 08:47:18

+0

這是Intent的行爲,使用「你的包名稱」作爲前綴以保持其獨特性,例如。 「com.google.result」。 – 2015-02-10 08:49:40

+0

k我會嘗試,,謝謝 – Kartiki 2015-02-10 08:52:03

0

使響應字符串靜態全局 public static Sting response; 添加此行如同 response = new GetPayment()。execute(WebUrl.RechargeServiceURL +「AddRecharge」);

和解析響應字符串喜歡這裏

  HttpEntity entity1 = (payment.respone).getEntity(); 
      InputStream stream = entity1.getContent(); 
      r = convertStreamToString(stream); 
       JSONObject jo = new JSONObject(r); 
      s= (Integer) jo.get("Flag"); 
      Log.d("json result is:", r); 
     statusCode = response.getStatusLine().getStatusCode(); 

     } catch (Exception e) { 
      e.printStackTrace(); 

     Log.d("error", "code"+0); 
    } 

放converttostream方法在此actvity

public static String convertStreamToString(InputStream is) { 
    BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
    StringBuilder sb = new StringBuilder(); 
    String line = null; 
    try { 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     try { 
      is.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 
    return sb.toString(); 
} 
+0

請參閱編輯後 – Kartiki 2015-02-10 09:56:32

0

有多種方法來做到這一點,最好的方法之一就是寫你自己的界面。

public interface MyInterface{ 
    public void getResult(String result); 
} 

現在在您的Payment類中創建接口myInterface的局部變量並通過更改您的構造函數來初始化它。

private MyInterface myInterface; 
public Payment(Context context,String mobNumber,String amount,MyInterface interface){ 
     db = new DatabaseHandler(context); 
     INSTANCE=this; 

     this.mobNumber = mobNumber; 

    this.amount = amount; 
    this.myInterface=myInterface 

    new GetPayment().execute(WebUrl.RechargeServiceURL + "AddRecharge"); 
} 

並調用onPostExecute這樣的方式,方法()

if (result != null) { 
     try { 
       myInterface.getResult(result);  
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
} else { 
     Toast.makeText(context, "something went wrong", Toast.LENGTH_LONG).show();  
} 

現在,在你的活動只是實現這個接口和getResult()方法。

編輯:

現在,它更容易爲你。只需在所有片段中實現MyInterface。

public class Fragment1 extends Fragment implements MyInterface{ 

    //Implemented method 
    public void getResult(String result){ 
     //access your result from here 
    } 
} 
+0

請現在看我的帖子。 – Kartiki 2015-02-10 09:57:47

+0

@Kartiki檢查更新的解決方案。 – dhuma1981 2015-02-10 10:15:34

+0

對不起。我寫了這個公共接口MyInterface public void getResult(String result); }如果我添加MyInterface接口這個構造函數然後我如何改變在每個片段 – Kartiki 2015-02-10 10:33:33

相關問題