gpt4 book ai didi

java - 将 json 的特定值传递给另一个 Activity

转载 作者:行者123 更新时间:2023-12-02 01:38:16 26 4
gpt4 key购买 nike

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

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

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

}
}
}

最佳答案

只要按照这个example并在CustomArrayAdapter中添加此方法

Offer getItem(position){
return items.get(position);
}

并在onItemSelected中添加此代码

void onItemSelected(parent,view,position,id){
Offer offer=customArrayAdapter.getItem(position);
}

如果这有效,那么您可以将 Offer 转换为您的 Client 类。希望这可能有所帮助

关于java - 将 json 的特定值传递给另一个 Activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57506167/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com