Home > Enterprise >  Display text and json on activity Android Studio Java
Display text and json on activity Android Studio Java

Time:05-28

so, I wrote a code where I get informations from a database about food.I'm asking If I can display some text with that ListView that I display.For example look here : app photo
Here are some numbers and I wanna write to all of them their description: Protein, Energy, etc. Here is the code that I wrote :

 package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;

public class LF1Activity extends AppCompatActivity {


    private String TAG = MainActivity.class.getSimpleName();
    private ListView lv;

    ArrayList<HashMap<String, String>> resultList;

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        super.onOptionsItemSelected(item);
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lf1);



        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        if (getSupportActionBar() != null){
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }




        resultList = new ArrayList<>();
        lv = (ListView) findViewById(R.id.list);
        new GetContacts().execute();
    }



    private class GetContacts extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(LF1Activity.this,"Json Data is downloading",Toast.LENGTH_LONG).show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            HttpHandler sh = new HttpHandler();
            // Making a request to url and getting response
            String url = "https://wger.de/api/v2/ingredient/?language=2&limit=11865";
            String jsonStr = sh.makeServiceCall(url);

            Log.e(TAG, "Response from url: "   jsonStr);
            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray results = jsonObj.getJSONArray("results");

                    // looping through All Contacts
                    for (int i = 0; i < results.length(); i  ) {
                        JSONObject c = results.getJSONObject(i);
                        String name = c.getString("name");
                        String fat = c.getString("fat");
                        String protein = c.getString("protein");
                        String energy = c.getString("energy");
                        String carbohydrates = c.getString("carbohydrates");
                        String carbohydrates_sugar = c.getString("carbohydrates_sugar");
                        String fat_saturated = c.getString("fat_saturated");
                        String fibres = c.getString("fibres");
                        String sodium = c.getString("sodium");




                        // tmp hash map for single contact
                        HashMap<String, String> result = new HashMap<>();

                        // adding each child node to HashMap key => value
                        result.put("name",name);
                        result.put("fat", fat);
                        result.put("protein",protein);
                        result.put("energy",energy);
                        result.put("carbohydrates", carbohydrates);
                        result.put("carbohydrates_sugar",carbohydrates_sugar);
                        result.put("fat_saturated", fat_saturated);
                        result.put("fibres",fibres);
                        result.put("sodium", sodium);


                        // adding contact to contact list
                        resultList.add(result);
                    }
                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: "   e.getMessage());
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Json parsing error: "   e.getMessage(),Toast.LENGTH_LONG).show();
                        }
                    });

                }

            } else {
                Log.e(TAG, "Couldn't get json from server.");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Couldn't get json from server. Check LogCat for possible errors!",
                                Toast.LENGTH_LONG).show();
                    }
                });
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            ListAdapter adapter = new SimpleAdapter(LF1Activity.this, resultList,
                    R.layout.list_item_nutrition, new String[]{ "name","fat","energy","protein","carbohydrates","carbohydrates_sugar","fat_saturated","fibres","sodium"},
                    new int[]{R.id.name, R.id.fat,R.id.protein,R.id.energy,R.id.carbohydrates,R.id.carbohidrates_sugar,R.id.fat_saturated,R.id.fibres,R.id.sodium});
            lv.setAdapter(adapter);
        }
    }
} 
                                                                 

Here is the activity where I display them all:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".LF1Activity">


    <ListView
        android:id="@ id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="56dp"

        app:layout_constraintTop_toTopOf="parent"
        tools:layout_editor_absoluteX="0dp" />


    <RelativeLayout
        android:id="@ id/relativeLayout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">


        <androidx.appcompat.widget.Toolbar
            android:id="@ id/toolbar"
            android:layout_width="411dp"
            android:layout_height="wrap_content"
            android:background="#000000" />


        <ImageView
            android:id="@ id/back_to_home"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:minWidth="40dp"
            android:minHeight="45dp"
            android:paddingTop="15dp"
            android:src="@drawable/ic_back" />

        <TextView

            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingTop="16dp"
            android:text="Exercise Database"
            android:textAlignment="center"
            android:textColor="#FFFFFFFF"
            android:textSize="20sp"
            android:textStyle="bold" />


    </RelativeLayout>


</androidx.constraintlayout.widget.ConstraintLayout>

Here is the list where I store them :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="@dimen/activity_horizontal_margin">


    <TextView
        android:paddingTop="10dp"
        android:id="@ id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/colorAccent"
        android:text="Name:"/>

    <TextView
        android:id="@ id/energy"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#5d5d5d"
        android:textStyle="bold"
        android:paddingTop="10dp"
        android:text="Energy:"
        />

    <TextView
        android:id="@ id/protein"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#5d5d5d"
        android:textStyle="bold"
        android:text="Protein:"
        />

    <TextView
        android:id="@ id/carbohydrates"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#5d5d5d"
        android:textStyle="bold"
        android:text="Carbohydrates:"
        />

    <TextView
        android:id="@ id/carbohidrates_sugar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#5d5d5d"
        android:textStyle="bold"
        android:text="Carbohydrates from sugar:"
        />

    <TextView
        android:id="@ id/fat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#5d5d5d"
        android:textStyle="bold"
        android:text="Fat:"
        />

    <TextView
        android:id="@ id/fat_saturated"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#5d5d5d"
        android:textStyle="bold"
        android:text="Saturated Fat:"
        />

    <TextView
        android:id="@ id/fibres"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#5d5d5d"
        android:textStyle="bold"
        android:text="Fibres:"
        />

    <TextView
        android:id="@ id/sodium"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#5d5d5d"
        android:textStyle="bold"
        android:text="Sodium:"
        />


</LinearLayout>

CodePudding user response:

try using

result.put("fat", "Fat :" fat);
  • Related