1

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);
Community
  • 1
  • 1
  • In your NextActivity(SearchResults.class i think) just use: *String id = intent.getStringExtra("id");* and *String name = intent.getStringExtra("name");* to get your data – Rami Dec 09 '14 at 10:20
  • i already did but i want to diplayit in listview,and chek my previous question –  Dec 09 '14 at 10:32
  • @EbinJames how to do this can you tell? –  Dec 09 '14 at 10:37
  • Where is the data that you want to pass? @EbinJames i don't think he need to use a BroadCastReceiver to pass data from activity to another. – Rami Dec 09 '14 at 10:38
  • @Rami the data i want to pass,is i am getting from response,see my previous question –  Dec 09 '14 at 10:40
  • 2
    1) send the data as an extra (like you have done "whole"-json). 2) get the json value in your second activity (with intent.getStringExtra...). 3) follow this link to know how to build list from json: http://stackoverflow.com/questions/21662673/how-to-display-fetched-json-data-into-listview-using-baseadapter – Rami Dec 09 '14 at 10:50
  • @Johnson: You can use intent for passing the data from one activity to another, on the second activity read the data from intent and dispaly it. change this to "final String msg = jobj.getString("searchresult"); return json.getString(TAG_SUCCESS);" to "final String msg = jobj.getString("searchresult"); return msg;" and pass this string "msg" in your onPostExecute – Ebin James Dec 09 '14 at 10:51
  • @Rami i know how to get data in listview but i dont know how to fetch data which i got response in diffrenet activity..see my question edited –  Dec 09 '14 at 10:58
  • You have the data and you know how to build your list from the data, so whats the problem? i haven't understand what's your question. And what do you mean by *"i got response in diffrenet activity"* ? – Rami Dec 09 '14 at 11:04
  • did you check my previous question?there i mean suppose in response i am getting names,so that names i want to display in next activity..is it possible? –  Dec 09 '14 at 11:07
  • Sorry but this is a very strange conversation. As indeed it's unclear what the exact problem is and all relevant remarks have been made already. But to repeat: If you know how to get the data in a listview then do you mean data from json text? As if you have json text in your activity you can send it to the next activity with `intent.putExtra("json", json.toString);`. And retrieve it with `String json = intent.getStringExtra("json");`. So now you have all json data in the next activity. Now what is exactly your problem? And no, i did not check your previous question. Don't ask such things. – greenapps Dec 09 '14 at 11:24
  • i sadi to check prev question cuz it will make clear to understnd..thnks dear –  Dec 09 '14 at 11:30
  • `I dont know how to do that` what do not you know? you have already sent it to next activity. can you tell what exactly your problem is ? – mmlooloo Dec 13 '14 at 17:46
  • the problem is its displaying single object only,not whole json objects –  Dec 13 '14 at 18:52
  • what happens if you replace `return json.getString(TAG_SUCCESS);` by `return msg;` – mmlooloo Dec 13 '14 at 20:12
  • What's value in TAG_SUCCESS? – MysticMagicϡ Dec 19 '14 at 13:19

6 Answers6

3

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 .....

lalit vasan
  • 450
  • 3
  • 6
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!

Ε Г И І И О
  • 11,199
  • 1
  • 48
  • 63
1

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");
neferpitou
  • 1,642
  • 2
  • 20
  • 26
1

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)

Unii
  • 1,587
  • 15
  • 33
0

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.

Tíbó
  • 1,188
  • 13
  • 28
0

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);