我正在构建一个带有列表视图的android应用程序,当单击一个项目时,它会打开另一个列表视图。我通过存储在应用程序资源的strings.xml文件中的一些字符串数组来完成此操作。

但是现在我想通过我创建的API获取数据项,并给出JSON对象。我不确定如何获取JSON对象并在列表视图中以列表项的形式查看课程名称。

单击“化学”(在MainActivity中)时,我想从SecondActivity中的“ http://alvideobackend.azurewebsites.net/lesson/Chemistry”中获取课程名称;单击“物理”(在MainActivity中)中,单击SecondActivity中的“ http://alvideobackend.azurewebsites.net/lesson/Physics”中的课程名称。

以下是我的MainActivity.java和SecondActivity.java,以及我尝试过的内容

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>

最佳答案

根据您的URL“ http://alvideobackend.azurewebsites.net/lesson/Chemistry”中的内容,您应该创建一个带有4个参数(_id,subject,lessonNo,lessonName)的Lesson类。然后,您可以调用API并使用Gson解析结果,如下所示:

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


然后,您可以创建一个自定义适配器,该适配器采用完整的课程arraylist或从课程数组列表中创建字符串数组列表,并像在示例中一样使用公用的ArrayAdapter。

我希望这有帮助!

09-28 05:52