How to display response in next activity

2020-08-02 09:58发布

问题:

In my application,I am working on searching module my previous question is How to show json response in other activity? for that I send request in server and after that I am getting response and in response I get some data,and that data I want to display in next page,I dont know how to do that,can any one help?

class AttemptLogin extends AsyncTask<String, String, String> {

    boolean failure = false;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Processing..");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @SuppressWarnings("unused")
    @Override
    protected String doInBackground(String...args) {
        //Check for success tag
        //int success;
        Looper.prepare();
        String userids = strtext.toString();


        String contri=spcountry.getText().toString();
        String states=spstate.getText().toString();
        String city=spcity.getText().toString();

        System.out.println("Email : " + userids);
        System.out.println("Email : " + agesfrom);
        System.out.println("Days : " + agesto);
        System.out.println("Months : " + heightfroms);
        System.out.println("Years : " + heighttos);
        System.out.println("User : " + language);
        System.out.println("Password : " + religion);
        System.out.println("Gender : " + marriage);
        System.out.println("First NM : " + contri);
        System.out.println("Last NM : " + states);
        System.out.println("Profile : " + city);*/



         try {
             //Building Parameters


             List<NameValuePair> params = new ArrayList<NameValuePair>();
             params.add(new BasicNameValuePair("user_login_id", userids));
            /* params.add(new BasicNameValuePair("age_from", agesfrom));
             params.add(new BasicNameValuePair("age_to", agesto));
             params.add(new BasicNameValuePair("height_from", heightfroms));
             params.add(new BasicNameValuePair("height_to", heighttos));
             params.add(new BasicNameValuePair("language", language));
             params.add(new BasicNameValuePair("religion", religion));
             params.add(new BasicNameValuePair("maritalstatus", marriage));
             params.add(new BasicNameValuePair("country", contri));
             params.add(new BasicNameValuePair("state", states));
             params.add(new BasicNameValuePair("city", city));
             */

             params.add(new BasicNameValuePair("version", "apps"));

             Log.d("request!", "starting");
             // getting product details by making HTTP request
            json = jsonParser.makeHttpRequest (
                 SEARCH_URL, "POST", params);

             //check your log for json response
             Log.d("Request attempt", json.toString());


             final String str = json.toString();

             JSONObject jobj = new JSONObject(json.toString());
             final String msg = jobj.getString("searchresult");

             return json.getString(TAG_SUCCESS);
             }catch (JSONException e) {
             e.printStackTrace();
         }
         return null;
    }

    // After completing background task Dismiss the progress dialog

    protected void onPostExecute(String file_url) {
        //dismiss the dialog once product deleted
         pDialog.dismiss();

            Intent intent=new Intent(getActivity(),SearchResults.class);
            intent.putExtra("id", strtext);
            intent.putExtra("whole", json.getString(TAG_SUCCESS));
            startActivity(intent);

}}

Searchresult.java

    Id=this.getIntent().getStringExtra("id");
    System.out.println("searching id"+Id);
    results=this.getIntent().getStringExtra("whole");
    System.out.println("Results"+results);
    nomathc=(TextView)findViewById(R.id.no_match);

回答1:

show response in next activity can be done in following ways

Solution 1 response comes in string so pass whole response to next activity by using

     intent.putExtras("Key",response);

Solution 2 make a singleton class of getter setter , by using this class u can set and get values throughout our application .

like this

step 1

public class SingleObject {

 //create an object of SingleObject
 private static SingleObject instance = new SingleObject();

 private String name;
 private String age;

 //make the constructor private so that this class cannot be
 //instantiated
   private SingleObject(){}

 //Get the only object available
 public static SingleObject getInstance(){
  return instance;
 }

  // here u can declare getter setter


public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getAge() {
    return age;
}

public void setAge(String age) {
    this.age = age;
}

}

step 2 use it in first activity like this

 Singleton tmp = Singleton.getInstance( );
  tmp.setName(""); 

step 3

and in next activity like this

  Singleton tmp = Singleton.getInstance( );
  String name =  tmp.getName;

Solution 3 : Make a static Arraylist of hashmap and use it in any activity

or there may be more solutions .....



回答2:

As far as I can see, all you need to know is how to bind your JSON result to a list view. If that's what you meant, read on...

I hope you already have a listview in your XML view for SearchResults activity. If not add one (say R.id.listView1).

Then create a row_listitem.xml file to format how one item on the list looks like.

<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/item_name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/item_location"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
        <TextView
            android:id="@+id/item_mothertongue"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
        ...
    </LinearLayout>
</RelativeLayout>

Now you need to create a custom adapter (say ResultAdapter).

public class ResultAdapter extends BaseAdapter {

    private JSONArray jsonArray;
    private LayoutInflater inflater = null;

    public ResultAdapter(Activity a, JSONArray b) {
        jsonArray = b;
        inflater = (LayoutInflater)a.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {
        return title.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View vi = convertView;
        if (convertView == null)
            vi = inflater.inflate(R.layout.row_listitem, null);

        try {
            JSONObject jsonObject = jsonArray.getJSONObject(position);

            TextView name = (TextView) vi.findViewById(R.id.item_name);
            String nameText = jsonObject.getString("name").toString();
            name.setText(nameText);

            TextView location = (TextView) vi.findViewById(R.id.item_location);
            String locationText = jsonObject.getString("location").toString();
            location.setText(locationText);

            ...

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

        return vi;
    }
}

Then you can modify your SearchResults activity.

public class SearchResults extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_searchresults);
        ListView list = (ListView) findViewById(R.id.listView1);
        String results = this.getIntent().getStringExtra("whole");

        JSONArray jsonArray = new JSONArray(results);
        ResultAdapter adapter = new ResultAdapter(SearchResults.this, jsonArray);
        list.setAdapter(adapter);
    }

    ...

}

The code isn't checked for compilation errors. But you get the drift I guess. Cheers!



回答3:

Store the object in a static Variable that requires two Parameter (Object and Unique Key).

// This class will hold the OBJECT containing a key in order to Access the
//location in our Custom Stack 
class Holder{
    private Object obj = null;
    private String key = null;
    public Holder(Object obj, String key){
       this.obj = obj;
       this.key = key;
    }
}

// This will serve as the storage for your JSON value
class GlobalStorage{
  public static ArrayList<Holder> stack = new ArrayList<Holder>();

  public static Object getValue(String key){
    for(int x = 0 ; x < stack.size() ; x++){
        if(stack.get(x).equals(key)){
           return stack.get(x);
        }     
     }
    return null;
  }

}


//In your OnPost
protected void onPostExecute(String file_url){
// your own code here ..
 GlobalStorage.add(new Holder("HI THIS IS MY JASON RESPONSE","whole"));
// your own code here..
}

Searchresult.java

 // myJson holds the value
 String myJson = (String)GlobalStorage.getValue("whole");


回答4:

use bundle to move your response from one activity to another

-create class that implements Parcelable

 public class ResponseData implements Parcelable{}

-Next save it in intent:

intent.putExtra(key, new ResponseData(someDataFromServer));

-step - retrive it:

 Bundle data = getIntent().getExtras(); ResponseData response=
 Response response =(ResponseData ) data.getParcelable(key);

-display it:

 textView.setText(data from response);

After that add it to an adapter to display it for the user

In other case you can save it in application context or database (not recommended)



回答5:

Broadcast notifications:

protected void onPostExecute(String file_url) {
    //dismiss the dialog once product deleted
     pDialog.dismiss();

        Intent intent=new Intent(getActivity(),SearchResults.class);
        sendNotificationResponse(json.getString(TAG_SUCCESS));
        startActivity(intent);
}

private void sendNotificationResponse(String response) {
        Intent intent = new Intent("KEY_INTENT");
        intent.putExtra("KEY_RESPONSE", response.toString());
        LocalBroadcastManager.getInstance(getActivity()).sendBroadcast(intent);
}

Then in SearchResult.java:

// handler for received intent
private BroadcastReceiver responseReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            String response = extras.getString("KEY_RESPONSE");

            //If you want it back as a JSON object
            JSONObject object = new JSONObject(response);

            //DO SOMETHING WITH THIS RESPONSE HERE

        }
    }
};

@Override
public void onResume() {
    super.onResume();
    LocalBroadcastManager.getInstance(this).registerReceiver(responseReceiver,
            new IntentFilter("KEY_INTENT"));
}

@Override
public void onDestroy() {
    super.onDestroy();
    // Unregister since the activity is not visible
    LocalBroadcastManager.getInstance(this).unregisterReceiver(responseReceiver);
}

I believe that should do the trick.



回答6:

I simply added hashmap and call it next activity its working fine,

   HashMap<String, String> hmp = new HashMap<String, String>();
                 hmp.put(TAG_AGE, Ages+" years");
                 hmp.put(TAG_CAST, Casts);
                 hmp.put(TAG_IMAGE, Images);
                 hmp.put(TAG_LOCATION, Locations);
                 hmp.put(TAG_MATCH_ID, match_Detail_id);
                 hmp.put(TAG_NAME, Names);
                 hmp.put(TAG_PROFILE, Profiles);

                 alhmp.add(hmp);

in next activity

    Intent intent = getIntent();
    aList = (ArrayList<HashMap<String, String>>) intent.getSerializableExtra("match_data");
    adapter = new CustomAdapterSearch(SearchResults.this, aList);
   setListAdapter(adapter);