简体   繁体   中英

Parsing JSON objects in Android Application

I am building an android application with a list view which opens up another listview when an item is clicked. I have done this through a few string arrays stored in the strings.xml file in the app resources.

But now I want to get the data items through an API which I have created, giving out JSON objects. I am not sure how I can get the JSON objects and view the lesson names as list items in the list view.

I want to get the lessonNames from " http://alvideobackend.azurewebsites.net/lesson/Chemistry " in the SecondActivity when clicked on "Chemistry"(in MainActivity) and " http://alvideobackend.azurewebsites.net/lesson/Physics " in the SecondActivity when clicked on "Physics"(in MainActivity)

The following are my MainActivity.java and SecondActivity.java with what I have tried

MainActivity.java

package com.example.acer.videoapp;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.support.v7.widget.Toolbar;

public class MainActivity extends AppCompatActivity {

    Toolbar toolbar;
    ListView listView;

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



        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle(getResources().getString(R.string.app_name));
        listView = (ListView) findViewById(R.id.listView);


        ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_expandable_list_item_1,getResources().getStringArray(R.array.subjects));

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                Intent intent = new Intent(MainActivity.this,SecondActivity.class);
                intent.putExtra("Subject",listView.getItemAtPosition(i).toString());
                startActivity(intent);
            }
        });
        listView.setAdapter(mAdapter);
    }


}

SecondActivity.java

package com.example.acer.videoapp;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class SecondActivity extends AppCompatActivity {
    Toolbar toolbar1;
    ListView listView1;

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

        toolbar1 = (Toolbar) findViewById(R.id.toolbar1);
        listView1 = (ListView) findViewById(R.id.listView1);

        Bundle bundle = getIntent().getExtras();
        if(bundle!=null){
            toolbar1.setTitle(bundle.getString("Subject"));

            if(toolbar1.getTitle().toString().equalsIgnoreCase("Chemistry")){

               //new JSONTask().execute("http://alvideobackend.azurewebsites.net/lesson/Chemistry");

               ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(SecondActivity.this,android.R.layout.simple_expandable_list_item_1,getResources().getStringArray(R.array.Chemistry));

                listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                        Intent intent1 = new Intent(SecondActivity.this, ThirdActivity.class);
                        intent1.putExtra("Lesson", listView1.getItemAtPosition(i).toString());
                        startActivity(intent1);
                    }
                });
               listView1.setAdapter(mAdapter);

            }
            else if(toolbar1.getTitle().toString().equalsIgnoreCase("Physics")){
                ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(SecondActivity.this,android.R.layout.simple_expandable_list_item_1,getResources().getStringArray(R.array.Physics));

                listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int i, long id) {
                        Intent intent1 = new Intent(SecondActivity.this, ThirdActivity.class);
                        intent1.putExtra("Lesson", listView1.getItemAtPosition(i).toString());
                        startActivity(intent1);
                    }
                });
                listView1.setAdapter(mAdapter);

            }
        }


    }

    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.connect();

                InputStream stream = connection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(stream));

                StringBuffer buffer = new StringBuffer();
                String line = "";
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }

                String finalJson = buffer.toString();
                JSONObject ParentObject = new JSONObject(finalJson);
                JSONArray ParentArray = ParentObject.getJSONArray("");


                for(int i=0; i<ParentArray.length();i++) {

                    JSONObject finalObject = ParentArray.getJSONObject(i);


                    String subject = finalObject.getString("subject");
                    Integer lessonNo = finalObject.getInt("lessonNo");
                    String lessonName = finalObject.getString("lessonName");


                }
                //return lessonName;

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }


        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }
    }

}

strings.xml

<resources>
<string name="app_name">VideoApp</string>
<string name="action_settings">Settings</string>
<string name="title_activity_second">SecondActivity</string>
<string name="title_activity_third">ThirdActivity</string>

<string-array name="subjects">
    <item>Chemistry</item>
    <item>Physics</item>
</string-array>

<string-array name="Physics">
    <item>1. Measurement</item>
    <item>2. Mechanics</item>
    <item>3. Oscillations and Waves</item>
    <item>4. Thermal Physics</item>
    <item>5. Gravitational Field</item>
    <item>6. Electrostatic Field</item>
    <item>7. Magnetic Field</item>
    <item>8. Current Electricity</item>
    <item>9. Electronics</item>
    <item>10. Mechanical Properties of Matter</item>
    <item>11. Matter and Radiation</item>
</string-array>

<string-array name="Chemistry">
    <item>1. Atomic structure</item>
    <item>2. Structure and bonding</item>
    <item>3. Chemical calculations</item>
    <item>4. Gaseous state of matter</item>
    <item>5. Energetics</item>
    <item>6. Chemistry of s,p and d block elements</item>
    <item>7. Basic concepts of organic chemistry</item>
    <item>8. Hydrocarbons and halohydrocarbons</item>
    <item>9. Oxygen containing organic compounds</item>
    <item>10. Chemical kinetics</item>
    <item>11. Equilibrium</item>
    <item>12. Electro chemistry</item>
    <item>13. Industrial chemistry and Environmental pollution</item>
</string-array>

</resources>

You may use the Retrofit library for your problem.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://alvideobackend.azurewebsites.net/")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

LessonService service = retrofit.create(LessonService.class);

public interface LessonService {
  @GET("lesson/{lesson}/")
  Call<List<Lesson>> listOfLessons(@Path("lesson") String lesson);
}

If you have already defined the Lesson class as a POJO class. The response coming from the Retrofit request will automatically be parsed into lesson object 's attributes.

Further info: http://square.github.io/retrofit/

according to what you have in your url " http://alvideobackend.azurewebsites.net/lesson/Chemistry ", you should create a Lesson class with 4 parameters (_id, subject, lessonNo, lessonName). Then you can call your API and parse the result using Gson like this:

ArrayList<Lesson> lessonList = new ArrayList<>();
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<Lesson>>(){}.getType();
lessonList = gson.fromJson(json, type);

Then you can create a custom adapter that takes a full lesson arraylist or create a string array list from your lesson array list and use a common ArrayAdapter as you have done in your example.

I hope this helps!

您可以尝试使用Retrofit http://square.github.io/retrofit/ ,通过此lib,您可以自动解析对Java对象的Json响应。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM