首页 > 解决方案 > 将某个 json 值传递给另一个活动

问题描述

我正在构建一个应用程序来将图像上传到我的公司服务器,现在正在使用来自登录屏幕的数据和 2 个 Spinner 使用 URI.builder 生成所述上传的 URL,这些微调器位于单独的活动 (TimeLogActvity) 和 URI 中.Builder 在(Camra Activity) 目前来自微调器的数据正在使用intents.and 使用getSelectedItem.toString 将数据传递给URI.builder 中的字符串和calll 传递给URI.builder,

现在我的问题是,我正在使用来自服务器的 JSON 数据来填充微调器,所以一个微调器有一个客户端 Name ,我无法弄清楚的问题是我必须将一个值传递给 uri.builder,但是json 对每个客户端有 2 个值,名称及其客户端 ID,所以我想要做的是微调器必须显示客户端名称,但传递给 uri 构建器的数据只能是客户端 ID,我试图用谷歌搜索这个但我找不到任何有帮助的东西

活动 TmeLogActivity 包含微调器

public class TimeLogActivity extends AppCompatActivity {
Spinner spinner;
    Spinner spinner2;
    String URL="placeURLHERE";
    String URL2="PLACEURLHERE";
    ArrayList<String> CountryName;
    ArrayList<String> ClientName;
    String Item;
    String Item2;


    @Override
    protected void onCreate(Bundle savedInstanceState) {


        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_time_log);
        CountryName=new ArrayList<>();
        ClientName=new ArrayList<>();
        spinner=findViewById(R.id.spinner);
        spinner2=findViewById(R.id.spinner2);
        Button button23=findViewById(R.id.button1234);
        button23.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {


                Intent intent=new Intent(TimeLogActivity.this,
                        CameraActivity.class);
                intent.putExtra("Spinner", Item);
                intent.putExtra("Spinner2", Item2);

                startActivity(intent);
            }
        });


        loadSpinnerData(URL);
        loadSpinnerData2(URL2);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String country=spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString();
                Toast.makeText(getApplicationContext(), country, Toast.LENGTH_LONG).show();
                Item=spinner.getSelectedItem().toString();


            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {


            }
        });
        spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String country=spinner2.getItemAtPosition(spinner2.getSelectedItemPosition()).toString();
                Toast.makeText(getApplicationContext(), country, Toast.LENGTH_LONG).show();
                Item2=spinner2.getSelectedItem().toString();


            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {


            }

        });

    }

    private void loadSpinnerData(String url) {

        RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
        StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                String array=response.substring(47);


                try {
                    JSONObject jsonObject=new JSONObject(array);

                    if (jsonObject.getInt("success") == 1) {

                        JSONArray jsonArray=jsonObject.getJSONArray("Name");
                        for (int i=0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject1=jsonArray.getJSONObject(i);

                            String country=jsonObject1.getString("Country");
                            CountryName.add(country);
                        }
                    }
                    spinner.setAdapter(new ArrayAdapter<String>(TimeLogActivity.this, android.R.layout.simple_spinner_dropdown_item, CountryName));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        int socketTimeout=30000;
        RetryPolicy policy=new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        stringRequest.setRetryPolicy(policy);

        requestQueue.add(stringRequest);


    }

    private void loadSpinnerData2(String url) {

        RequestQueue requestQueue=Volley.newRequestQueue(getApplicationContext());
        StringRequest stringRequest=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                String array=response.substring(47);


                try {
                    JSONObject jsonObject=new JSONObject(array);

                    if (jsonObject.getInt("success") == 1) {

                        JSONArray jsonArray=jsonObject.getJSONArray("Name");
                        for (int i=0; i < jsonArray.length(); i++) {
                            JSONObject jsonObject1=jsonArray.getJSONObject(i);

                            String clientName=jsonObject1.getString("ClientName");
                            ClientName.add(clientName);
                        }
                    }
                    spinner2.setAdapter(new ArrayAdapter<String>(TimeLogActivity.this, android.R.layout.simple_spinner_dropdown_item, ClientName));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        int socketTimeout=30000;
        RetryPolicy policy=new DefaultRetryPolicy(socketTimeout, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        stringRequest.setRetryPolicy(policy);

        requestQueue.add(stringRequest);
    }
}

CameraActivity 包含 URI.Builder 和上传、相机功能

public class CameraActivity extends AppCompatActivity implements View.OnClickListener {
    private final int PICK_IMAGE=12345;
    private final int REQUEST_CAMERA=6352;
    private static final int REQUEST_CAMERA_ACCESS_PERMISSION=5674;
    private Bitmap bitmap;

    String myURL;
    String clientId;
    String email;
    String pwd;


    private ImageView imageView;



    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        Intent intent = getIntent();
        clientId = intent.getStringExtra("clientId");
         email = intent.getStringExtra("email");
        pwd = intent.getStringExtra("pass");


        imageView=findViewById(R.id.imageView);
        Button fromCamera=findViewById(R.id.fromCamera);
        Button fromGallery=findViewById(R.id.fromGallery);
        Button upload=findViewById(R.id.upload);
        upload.setOnClickListener(this);
        fromCamera.setOnClickListener(this);
        fromGallery.setOnClickListener(this);
        Bundle extras = getIntent().getExtras();
        if(extras !=null) {
            String clientID = extras.getString("KEY");
        }



        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY)) {
            fromCamera.setVisibility(View.GONE);
        }

    }

    @Override
    public void onClick(View view) {



        switch (view.getId()) {
            case R.id.fromCamera:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                        && ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{Manifest.permission.CAMERA},
                            REQUEST_CAMERA_ACCESS_PERMISSION);
                } else {
                    getImageFromCamera();
                }
                break;
            case R.id.fromGallery:
                getImageFromGallery();
                break;
            case R.id.upload:
                if (bitmap != null)
                    uploadImageToServer();
                break;

        }


    }


    private void uploadImageToServer() {
        @SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HH_mm_ss");
        String currentTimeStamp = dateFormat.format(new Date());
        final ProgressDialog pd=new ProgressDialog(CameraActivity.this);
        pd.setMessage("Uploading, Please Wait....");
        pd.show();
        Intent intent = getIntent();
        String Item= intent.getStringExtra("Spinner");
        String Item2= intent.getStringExtra("Spinner2");


        Uri.Builder builder=new Uri.Builder();
        builder.scheme("https")
                .authority("www.smartpractice.co.za")
                .appendPath("files-upload-ruben.asp")
                .appendQueryParameter("MyForm", "Yes")
                .appendQueryParameter("ClientID",clientId)
                .appendQueryParameter("Username", email)
                .appendQueryParameter("Pwd", pwd)
        .appendQueryParameter("category",Item )
        .appendQueryParameter("client",Item2 );
        myURL=builder.build().toString();
        Toast toast = Toast.makeText(CameraActivity.this, myURL , Toast.LENGTH_LONG);
        toast.show();

        File imageFile=persistImage(bitmap,currentTimeStamp);

        Ion.with(this)
                .load(myURL)
                .uploadProgressDialog(pd)
                .setMultipartFile("SP-LOG", "image/jpeg", imageFile)


                .asString()


                .setCallback(new FutureCallback<String>() {
                    @Override
                    public void onCompleted(Exception e, String result) {
                     pd.cancel();
                        Toast.makeText(getApplicationContext(),"Uploaded",Toast.LENGTH_SHORT).show();

                    }
                });

    }

    private File persistImage(Bitmap bitmap, String name) {
        File filesDir=getApplicationContext().getFilesDir();
        File imageFile=new File(filesDir, name + ".jpg");

        OutputStream os;
        try {
            os=new FileOutputStream(imageFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
            os.flush();
            os.close();
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
        }

        return imageFile;
    }


    private void getImageFromCamera() {
        Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, REQUEST_CAMERA);
    }

    private void getImageFromGallery() {
        Intent intent=new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE) {
            if (resultCode == Activity.RESULT_OK) {
                try {
                    InputStream inputStream=getContentResolver().openInputStream(data.getData());
                    bitmap=BitmapFactory.decodeStream(inputStream);
                    imageView.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

            }
        } else if (requestCode == REQUEST_CAMERA) {
            if (resultCode == Activity.RESULT_OK) {
                Bundle extras=data.getExtras();
                bitmap=(Bitmap) extras.get("data");
                imageView.setImageBitmap(bitmap);
            }
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_CAMERA_ACCESS_PERMISSION) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getImageFromCamera();
            }
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        }
    }
}

标签: javaandroidjsonandroid-spinner

解决方案


听起来你没有很好地使用微调器,看看How to create Spinner-list using CustomAdapter in android,自定义适配器应该回答你的问题


推荐阅读