【问题标题】:How to access JSON response and display it in new activity in android?如何访问 JSON 响应并将其显示在 android 的新活动中?
【发布时间】:2016-01-15 06:25:24
【问题描述】:

当在 editText 字段中填写详细信息时,我从 PHP 获得 JSON 响应为 {"success":'Hi Namrata...'}。我想读取成功值并将其显示在新活动中,如果出现 {"error":'something occurred'} 我想在同一个活动中。我该怎么做。 这是我的 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);

    }
  }
}

【问题讨论】:

标签: php android json


【解决方案1】:

在你的 postexecute 方法中执行此操作

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

        }

参加另一个活动

String valueofsucess = getIntent().getStringExtra("sucessval");

【讨论】:

  • 我希望新活动的成功值不在同一个活动上。
  • 我正在进行新的活动,但我没有获得成功的价值。
  • 你有没有把第二行放在第二个活动上
  • 您必须将此行放在第二个活动中的 setContentView 之后
  • 我也是这样做的。仍然得到相同的结果。
【解决方案2】:

更改以下行 -

new JsonTask().execute.....

new JsonTask(MainActivity.this).execute

类JsonTask里面修改-

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

    Context context;

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

都一样

如下修改你的 onPostExecute() -

@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();
        }
    }

【讨论】:

  • @Namrata Singh: context = MainActivity.this 你传递给你的 AsyncTask
  • 它说“很遗憾,MyApplication 已停止”。
  • @Namrata Singh:你没有将上下文传递给 Asynck。我已经编辑了我的答案,看看我相信它会有所帮助:)
  • @NamrataSingh:请在聊天chat.stackoverflow.com/rooms/100739/…
  • 我没有足够的声望来聊天。我是新来的。
【解决方案3】:

我假设您正在开始项目,您是否可以开始迁移到一些网络库。喜欢Retrofit。因为它将帮助您在项目中运行更长时间。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 2012-06-05
    相关资源
    最近更新 更多