Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何访问JSON响应并在android的新活动中显示它?_Php_Android_Json - Fatal编程技术网

Php 如何访问JSON响应并在android的新活动中显示它?

Php 如何访问JSON响应并在android的新活动中显示它?,php,android,json,Php,Android,Json,当在editText字段中填写详细信息时,我从PHP获得的JSON响应为{“success”:“Hi Namrata…”}。我想读取成功值并在新活动中显示它,如果出现{“错误”:“发生了什么事”},我想在同一个活动中。。我该怎么做呢。 这是我的主要活动 public class MainActivity extends AppCompatActivity { public Button blogin;TextView content; public EditText uname, pass;

当在editText字段中填写详细信息时,我从PHP获得的JSON响应为{“success”:“Hi Namrata…”}。我想读取成功值并在新活动中显示它,如果出现{“错误”:“发生了什么事”},我想在同一个活动中。。我该怎么做呢。 这是我的主要活动

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

    }
  }
}
public类MainActivity扩展了AppCompatActivity{
公共按钮博客;文本查看内容;
公共编辑文本uname,pass;
@凌驾
创建时受保护的void(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=(按钮)findviewbyd(R.id.blogin);
blogin.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
新建JsonTask()。执行(“https://www.aboutmyclinic.com/test.php,uname.getText().toString(),pass.getText().toString());
}
});
}
公共类JsonTask扩展了异步任务{
@凌驾
受保护的字符串doInBackground(字符串…参数){
HttpURLConnection=null;
BufferedReader reader=null;
试一试{
URL=新URL(参数[0]);
connection=(HttpURLConnection)url.openConnection();
connection.setReadTimeout(10000);
连接。设置连接超时(15000);
connection.setRequestMethod(“POST”);
connection.setDoInput(true);
connection.setDoOutput(真);
Uri.Builder=新的Uri.Builder()
.appendQueryParameter(“firstParam”,参数[1])
.appendQueryParameter(“secondParam”,参数[2]);
//.appendQueryParameter(“类型”,参数[3]);
字符串查询=builder.build().getEncodedQuery();
OutputStream os=connection.getOutputStream();
BufferedWriter=新的BufferedWriter(
新的OutputStreamWriter(操作系统,“UTF-8”);
writer.write(查询);
writer.flush();
writer.close();
os.close();
connection.connect();
InputStream InputStream=connection.getInputStream();
StringBuffer=新的StringBuffer();
reader=新的BufferedReader(新的InputStreamReader(inputStream));
弦线;
而((line=reader.readLine())!=null){
buffer.append(第+行“\n”);
}
返回buffer.toString();
}捕获(格式错误){
e、 printStackTrace();
}捕获(IOE异常){
e、 printStackTrace();
}最后{
if(连接!=null){
连接断开();
}
if(读卡器!=null){
试一试{
reader.close();
}捕获(最终IOE例外){
}
}
}
返回null;
}
@凌驾
受保护的void onPostExecute(字符串结果){
super.onPostExecute(结果);
content.setText(结果);
}
}
}

在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");
换行-

new JsonTask().execute.....

在类JsonTask modify中-

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

    Context context;

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

我想你们马上就要开始这个项目了,你们可以开始迁移到一些网络库了吗。喜欢因为这将有助于您在项目中长期运行

    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);
    }
public类活动扩展AppCompative活动实现回调{
私人对话;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_改装);
提出请求(“ashish”、“ashish”);
}
私有void makeRequest(字符串用户名、字符串密码){
改装改装=新改装.Builder()
.baseUrl(“https://www.aboutmyclinic.com/")
.build();
服务=改装.create(服务.class);
用户=新用户(用户名、密码);
调用loginRequest=service.login(user.getFirstParam(),user.getSecondParam());
dialog=新建ProgressDialog(此);
setMessage(“登录”);
dialog.show();
loginRequest.enqueue(此);
}
@凌驾
公共响应(响应){
Log.i(“响应”,“响应+响应”);
Log.i(“Response”,“”+Response.body().toString());
试一试{
Log.i(“Response”,“”+Response.body().string());
}捕获(IOE异常){
e、 printStackTrace();
}
dialog.cancel();
}
@凌驾
失效时的公共无效(可丢弃的t){
Log.e(“错误”、“意外响应”);
dialog.cancel();
}
公共类用户{
字符串firstParam;
字符串secondParam;
公共用户(字符串用户名、字符串密码){
this.firstParam=用户名;
this.secondParam=密码;
}
公共字符串getFirstParam(){
返回firstParam;
}
public void setFirstParam(字符串firstParam){
this.firstParam=firstParam;
}
公共字符串getSecondParam(){
返回secondParam;
}
public void setSecondParam(字符串secondParam){
this.secondParam=secondParam;
}
}
}
公共接口服务{
@POST(“/test.php”)
公共调用登录(@Query(“firstParam”)字符串firstParam,@Query(“secondParam”)字符串secondParam);
}
请检查此项
@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();
        }
    }
    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);
    }