2

I am getting the JSON response from PHP as {"success":'Hi Namrata...'} when the details are filled out in the editText field. I want to read the success value and display it in the new activity and in case of {"error":'something happened'} I want to be on the same activity.. How can I do that. Here is my MainActivity

public class MainActivity extends AppCompatActivity {

public Button blogin;TextView content;
public EditText uname, pass;

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

    uname = (EditText) findViewById(R.id.uname);
    pass = (EditText) findViewById(R.id.pass);
    content=   (TextView)findViewById( R.id.content );
    blogin = (Button) findViewById(R.id.blogin);

    blogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            new JsonTask().execute("https://www.aboutmyclinic.com/test.php",uname.getText().toString(),pass.getText().toString());

        }
    });



}

public class JsonTask extends AsyncTask<String, String, String> {

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

        HttpURLConnection connection = null;
        BufferedReader reader = null;


        try {

            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.setReadTimeout(10000);
            connection.setConnectTimeout(15000);
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            Uri.Builder builder = new Uri.Builder()
                    .appendQueryParameter("firstParam", params[1])
                    .appendQueryParameter("secondParam", params[2]);
                    //.appendQueryParameter("type", params[3]);
            String query = builder.build().getEncodedQuery();
            OutputStream os = connection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(query);
            writer.flush();
            writer.close();
            os.close();


            connection.connect();



            InputStream inputStream = connection.getInputStream();
            StringBuffer buffer = new StringBuffer();

            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {

                buffer.append(line + "\n");
            }
            return buffer.toString();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {

                }
            }

        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        content.setText(result);

    }
  }
}
Namrata Singh
  • 203
  • 2
  • 8

3 Answers3

0

do this in your postexecute method

  @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
             JSONObject json=new JSONObject(result);
            String sucessvalue= json.getString("success");

          Intent i=new Intent(MainActivity.this,NewActivity.class);
          i.putExtra("sucessval",sucessvalue);
          startActivity(i);

        }

get in another activity

String valueofsucess = getIntent().getStringExtra("sucessval");
raj
  • 2,088
  • 14
  • 23
0

Change below line -

new JsonTask().execute.....

to

new JsonTask(MainActivity.this).execute

Inside the class JsonTask modify -

public class JsonTask extends AsyncTask<String, String, String> {

    Context context;

    JsonTask(Context context){
        this.context = context;
    }

rest all same

Modify your onPostExecute() as below -

@Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        String result = "error";
        try {
            JSONObject jObj = new JSONObject(s);
            if(jObj.has("success")){

                result = jObj.getString("success");
                startActivity(new Intent(context, NextActivity.class)
                .putExtra("result", result));
            }else{
                content.setText(result);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
kevz
  • 2,727
  • 14
  • 39
  • @Namrata Singh: context = MainActivity.this that u passed to ur AsyncTask – kevz Jan 15 '16 at 07:12
  • It says "Unfortunately, MyApplication has been stopped". – Namrata Singh Jan 15 '16 at 07:19
  • @Namrata Singh: well u didn't passed the context to Asynck. I've edit my answer check it out I'm sure it'll help :) – kevz Jan 15 '16 at 07:21
  • @NamrataSingh: plz lets talk in chat http://chat.stackoverflow.com/rooms/100739/how-to-access-json-response-and-display-it-in-new-activity-in-android – kevz Jan 15 '16 at 07:31
  • I don't have enough reputation to chat. I am new here. – Namrata Singh Jan 15 '16 at 07:42
  • @Namrata Singh: where u stuck at? – kevz Jan 15 '16 at 08:45
  • Error is - java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference – Namrata Singh Jan 15 '16 at 08:53
  • @Namrata Singh: I've moved the String result declaration outside if block can u plz check it now. – kevz Jan 15 '16 at 08:57
  • @NamrataSingh can you please try retrofit tutorials for beginners – silentsudo Jan 15 '16 at 09:06
  • @NamrataSingh: on which line r u getting the error? – kevz Jan 15 '16 at 09:07
  • @NamrataSingh you webservice define is wrong it does not stands properly for JSON format please check with you service developer :D – silentsudo Jan 15 '16 at 09:17
  • @kevz Now I'm getting a different error - java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.namrata.clinic/com.example.namrata.clinic.Login}: java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead. – Namrata Singh Jan 16 '16 at 05:48
  • @sector11 I'm not getting you and I'll try retrofit later. – Namrata Singh Jan 16 '16 at 05:48
0

I assume you are starting project right away can you start moving to some networking libraries. Like Retrofit. Because it will help you for longer run in project.

    public class RetrofitActivity extends AppCompatActivity implements Callback<ResponseBody> {

        private ProgressDialog dialog;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_retrofit);
            makeRequest("ashish", "ashish");
        }


        private void makeRequest(String userName, String password) {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("https://www.aboutmyclinic.com/")
                    .build();
            Service service = retrofit.create(Service.class);
            User user = new User(userName, password);
            Call<ResponseBody> loginRequest = service.login(user.getFirstParam(), user.getSecondParam());
            dialog = new ProgressDialog(this);
            dialog.setMessage("Logging in");
            dialog.show();
            loginRequest.enqueue(this);
        }

        @Override
        public void onResponse(Response<ResponseBody> response) {
            Log.i("Response", "" + response);
 Log.i("Response", "" + response.body().toString());
        try {
            Log.i("Response", "" + response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
            dialog.cancel();
        }

        @Override
        public void onFailure(Throwable t) {
            Log.e("Error", "Unexpected response");
            dialog.cancel();
        }

        public class User {
            String firstParam;
            String secondParam;

            public User(String userName, String password) {
                this.firstParam = userName;
                this.secondParam = password;
            }

            public String getFirstParam() {
                return firstParam;
            }

            public void setFirstParam(String firstParam) {
                this.firstParam = firstParam;
            }

            public String getSecondParam() {
                return secondParam;
            }

            public void setSecondParam(String secondParam) {
                this.secondParam = secondParam;
            }
        }
    }



    public interface Service {

        @POST("/test.php")
        public Call<ResponseBody> login(@Query("firstParam") String firstParam, @Query("secondParam")String secondParam);
    }
silentsudo
  • 6,730
  • 6
  • 39
  • 81