#android #json
#Android #json
Вопрос:
Я хочу установить цветное текстовое представление из результата Json (приведенный ниже код), если statusspp равен SPP, textcolor будет красным, если statusspp равен SP2D, textcolor будет зеленым. Можете ли вы мне помочь?
Это мой полный код: класс адаптера
public class AdapterSpp extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context context;
private LayoutInflater inflater;
List<DataSpp> data= Collections.emptyList();
DataSpp current;
int currentPos=0;
public AdapterSpp(Context context, List<DataSpp> data){
this.context=context;
inflater= LayoutInflater.from(context);
this.data=data;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.container_spp, parent,false);
MyHolder holder=new MyHolder(view);
return holder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
MyHolder myHolder= (MyHolder) holder;
DataSpp current=data.get(position);
myHolder.textSppName.setText(current.getTextSppName());
myHolder.textType.setText(current.getTextType());
myHolder.textSize.setText("Uraian : " current.getTextSize());
myHolder.textPrice.setText("Rp. " current.getTextPrice());
myHolder.textTgl.setText("Tgl.SPP : " current.getTextTgl());
myHolder.textPrice.setTextColor(ContextCompat.getColor(context, android.R.color.holo_red_light));
if(current.getTextType().equalsIgnoreCase("SPP")){
myHolder.textType.setTextColor(android.R.color.holo_red_light);
} else if(current.getTextType().equalsIgnoreCase("SP2D")){
myHolder.textType.setTextColor(android.R.color.holo_blue_light);
}
}
@Override
public int getItemCount() {
return data.size();
}
class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView textSppName;
TextView textSize;
TextView textType;
TextView textPrice;
TextView textTgl;
public MyHolder(View itemView) {
super(itemView);
textSppName = (TextView) itemView.findViewById(R.id.textFishName);
textSize = (TextView) itemView.findViewById(R.id.textSize);
textType = (TextView) itemView.findViewById(R.id.textType);
textPrice = (TextView) itemView.findViewById(R.id.textPrice);
textTgl = (TextView) itemView.findViewById(R.id.textTgl);
}
@Override
public void onClick(View v) {
Toast.makeText(context, "You clicked an item", Toast.LENGTH_SHORT).show();
}
}
}
И это мой класс Mainactivity :
открытый класс MainActivity расширяет AppCompatActivity {
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVSpp;
private AdapterSpp mAdapter;
SearchView searchView = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_main, menu);
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
searchView.setIconified(false);
}
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
@Override
protected void onNewIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
if (searchView != null) {
searchView.clearFocus();
}
new AsyncFetch(query).execute();
}
}
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn;
URL url = null;
String searchQuery;
public AsyncFetch(String searchQuery) {
this.searchQuery = searchQuery;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pdLoading.setMessage("tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
@Override
protected String doInBackground(String... params) {
try {
url = new URL("http://ditkeu.unair.ac.id/andro/sp2d-search.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
if (response_code == HttpURLConnection.HTTP_OK) {
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
return (result.toString());
} else {
return ("Connection error");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
@Override
protected void onPostExecute(String result) {
pdLoading.dismiss();
List<DataSpp> data = new ArrayList<>();
pdLoading.dismiss();
if (result.equals("no rows")) {
Toast.makeText(MainActivity.this, "No Results found for entered query", Toast.LENGTH_LONG).show();
} else {
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i ) {
JSONObject json_data = jArray.getJSONObject(i);
DecimalFormat formatter = new DecimalFormat("#,###,###");
DataSpp SppData = new DataSpp();
SppData.setTextSppName(json_data.getString("namapenerima"));
SppData.setTextSize(json_data.getString("uraianspp"));
SppData.setTextType(json_data.getString("statusspp"));
SppData.setTextPrice(formatter.format(json_data.getInt("jumlahtotal")));
SppData.setTextTgl(json_data.getString("tglsp2d"));
data.add(SppData);
}
mRVSpp = (RecyclerView) findViewById(R.id.fishPriceList);
mAdapter = new AdapterSpp(MainActivity.this, data);
mRVSpp.setAdapter(mAdapter);
mRVSpp.setLayoutManager(new LinearLayoutManager(MainActivity.this));
} catch (JSONException e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
Мой пользовательский адаптер :
public class DataSpp {
private String textSppName;
private String textSize;
private String textType;
private String textPrice;
private String textTgl;
//getters and setters
public String getTextSppName() {
return textSppName;
}
public void setTextSppName(String textSppName) {
this.textSppName = textSppName;
}
public String getTextSize() {
return textSize;
}
public void setTextSize(String textSize) {
this.textSize = textSize;
}
public String getTextType() {
return textType;
}
public void setTextType(String textType) {
this.textType = textType;
}
public String getTextPrice() {
return textPrice;
}
public void setTextPrice(String textPrice) {
this.textPrice = textPrice;
}
public String getTextTgl() {
return textTgl;
}
public void setTextTgl(String textTgl) {
this.textTgl = textTgl;
}
}
Комментарии:
1. где именно вы получаете цвет и где находится ваш textview?
2. выше я привел свой адаптер и код mainactivity .. пожалуйста, помогите
Ответ №1:
Я предполагаю, что вы показываете текст в TextView
TextView textView = (TextView)findViewById(R.id.your_textview);
if(sppData.statusName.equalsIgnoreCase("SPP"))
{textView.setTextColor(Color.RED)}
elseif(sppData.statusName.equalsIgnoreCase("SP2D"))
{textView.setTextColor(Color.GREEN)}
Комментарии:
1. да, вы правы, я показываю это в textview, но код textview находится в классе адаптера, поэтому SPP-данные не могут быть прочитаны. Есть решение, сэр?
2. вам нужно использовать класс модели для получения данных в вашем классе, содержащем TextView, поэтому каждый раз, когда у вас есть значение, оно будет установлено в классе модели, а затем вы можете получить объект, вызывающий метод getter из класса TextView, чтобы задать текст и реализовать условие, указанное выше для TextView в классе TextView
3. просто создайте класс с полями и сгенерируйте метод setter и getter (что можно легко сделать в Android Studio) , затем создайте два объекта класса model в классе adapter и классе JSON object, выполните описанную выше операцию
4. на самом деле я новичок в Java-коде Android, не могли бы вы дать мне пример кода для этого.
Ответ №2:
в вашем адаптере попробуйте добавить это :
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
MyHolder myHolder= (MyHolder) holder;
DataSpp current=data.get(position);
myHolder.textSppName.setText(current.SppName);
myHolder.textSize.setText("Status : " current.sizeName);
myHolder.textType.setText("Uraian : " current.catName);
myHolder.textPrice.setText("Rp. " current.price);
myHolder.textTgl.setText("Tgl.SPP : " current.tgl);
myHolder.textPrice.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));
if(current.statusName.equalsIgnoreCase("SPP"))
{
myHolder.textType.setTextColor(Color.RED);
} else if(current.statusName.equalsIgnoreCase("SP2D"))
{
myHolder.textType.setTextColor(Color.GREEN);
}
}
Ответ №3:
Создайте класс модели, подобный этому
public clas DataSpp{
private String textSppName;
private String textSize;
private String textType;
private String textPrice;
private String textTgl;
//getters and setters
public String getTextSppName() {
return textSppName;
}
public void setTextSppName(String textSppName) {
this.textSppName = textSppName;
}
public String getTextSize() {
return textSize;
}
public void setTextSize(String textSize) {
this.textSize = textSize;
}
public String getTextType() {
return textType;
}
public void setTextType(String textType) {
this.textType = textType;
}
public String getTextPrice() {
return textPrice;
}
public void setTextPrice(String textPrice) {
this.textPrice = textPrice;
}
public String getTextTgl() {
return textTgl;
}
public void setTextTgl(String textTgl) {
this.textTgl = textTgl;
}
}
В вашем ответе json
DataSpp SppData = new DataSpp();
sppData.setTextSppName(json_data.getString("namapenerima");
sppData.setTextSize(json_data.getString("uraianspp");
sppData.setTextType(json_data.getString("statusspp");
sppData.setTextPrice(formatter.format(json_data.getInt("jumlahtotal")));
sppData.setTextTgl(json_data.getString("tglspp");
В вашем on BindViewHolder после установки значений
if(current.textSppName.equalsIgnoreCase("SPP")){
myHolder.textType.setTextColor(Color.RED);
} else if(current.textSppName.equalsIgnoreCase("SP2D")){
myHolder.textType.setTextColor(Color.GREEN);
}
Комментарии:
1. я выполнил Jack, но по-прежнему textSppName не отображается, вот мой код :
2. Сначала проверьте свой ответ. Также опубликуйте свой ответ в формате Json.
3. @RizkiDeddySusanto: не могли бы вы опубликовать свой ответ, который вы получаете после вызова этой ссылки