У меня есть ссылка API, в которой есть элемент json с названием title, и я пытаюсь сохранить это значение в textview. Вот что у меня есть в моем основном коде активности, который должен отображать содержащуюся строку:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    JSONObject jObject;
    try {
        jObject = new JSONObject("https://chex-triplebyte.herokuapp.com/api/cats?page=0");
        String mResponse = jObject.getString("title");
        TextView t = (TextView) findViewById(R.id.title_image);
        t.setText(mResponse);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

Предоставленная мною ссылка API работает, поэтому вы можете увидеть заголовок значения, которое я пытаюсь получить.

0
user8452686 11 Сен 2017 в 06:36

3 ответа

Лучший ответ

Попробуй это:

  TextView t = (TextView) findViewById(R.id.title_image);
try {

                url = new URL("https://chex-triplebyte.herokuapp.com/api/cats?page=0");

                urlConnection = (HttpURLConnection) url
                        .openConnection();
                urlConnection.connect();

                InputStream in = urlConnection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(in));
                //InputStreamReader isw = new InputStreamReader(in);
                StringBuffer buffer = new StringBuffer();
                String line = "";
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }

                String JsonResponse= buffer.toString();

                JSONObject jsonobj = new JSONObject(JsonResponse);
                JSONArray jarray = jsono.getJSONArray("jsontitle");

            for (int i = 0; i < jarray.length(); i++) {
                JSONObject object = jarray.getJSONObject(i);


                 t.setText(object.getString("title"));


            }
           } catch (JSONException e) {
              e.printStackTrace();
            }

Но вы должны убедиться, что у вас есть правильный формат JSON, как это:

{jsontitle:[{"title":"Space Keybaord Cat","timestamp":"2017-09-11T04:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/space.jpg","description":"In space, no one can hear you purr."},{"title":"Jiji","timestamp":"2017-09-11T03:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/jiji.png","description":"You'd think they'd never seen a girl and a cat on a broom before"},{"title":"Limecat","timestamp":"2017-09-11T02:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/lime.jpg","description":"Destroyer of Clockspider and his evil followers, Limecat is the one true god."},{"title":"Astronaut Cat","timestamp":"2017-09-11T01:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/astronaut.jpg","description":"Houston, we have a purroblem"},{"title":"Grumpy Cat","timestamp":"2017-09-11T00:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/grumpy.jpg","description":"Queen of the RBF"},{"title":"Soviet cat","timestamp":"2017-09-10T23:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/soviet.jpg","description":"In soviet Russia cat pets you!"},{"title":"Serious Business Cat","timestamp":"2017-09-10T22:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/serious.jpg","description":"SRSLY GUISE"},{"title":"Sophisticated Cat","timestamp":"2017-09-10T21:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/sophisticated.PNG","description":"I should buy a boat"},{"title":"Shironeko","timestamp":"2017-09-10T20:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/shironeko.png","description":"The zen master kitty"},{"title":"Puss in Boots","timestamp":"2017-09-10T19:00:04Z","image_url":"https://triplebyte-cats.s3.amazonaws.com/puss.jpg","description":"Don't you dare do the litter box on me!"}]}
2
Orvenito 11 Сен 2017 в 04:01

Вам нужно сначала выполнить сетевой вызов, сначала разобрать его в JSONArray, а затем получить заголовок из JSON.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView t = (TextView) findViewById(R.id.title_image);
    RequestQueue queue = Volley.newRequestQueue(this);
    String url ="https://chex-triplebyte.herokuapp.com/api/cats?page=0";

   // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
        new Response.Listener<String>() {
      @Override
      public void onResponse(String response) {

           JSONArray jArray;
           try {
               jArray = new JSONArray(response);
               JSONObject jObject = jArray.getJSONObject(0);
               String mResponse = jObject.getString("title");

               t.setText(mResponse);
           } catch (JSONException e) {
               // TODO Auto-generated catch block
              e.printStackTrace();
           }
      }
      }, new Response.ErrorListener() {
     @Override
       public void onErrorResponse(VolleyError error) {

      }
   });
   // Add the request to the RequestQueue.
   queue.add(stringRequest);


}

Но это покажет только первый заголовок в массиве ответов. Если вы хотите показать все добавленные заголовки, вы можете зациклить массив

    JSONArray jArray;
    try {
        jArray = new JSONArray(response);
        String mResponse = "";
        for(int i=0 ;i<jArray.length();i++){
            JSONObject jObject = jArray.getJSONObject(i);
            mResponse += jObject.getString("title")+" ";
        }
        t.setText(mResponse);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
   }

Для использования залпа необходимо включить его в зависимости в build.gradle приложения

dependencies {
.
.
compile 'com.android.volley:volley:1.0.0'
.
.
}
1
Shriyansh Gautam 11 Сен 2017 в 04:01

Попробуй это...

< Сильный > MainActivity.java

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {

private String TAG = MainActivity.class.getSimpleName();
private ListView listView;
List<RowItem> rowItems;

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

    rowItems = new ArrayList<RowItem>();
    listView = (ListView) findViewById(R.id.item_list);

    new GetList().execute();
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
                        long id) {
    Toast toast = Toast.makeText(getApplicationContext(),
            "Item " + (position + 1) + ": " + rowItems.get(position),
            Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    toast.show();
}

class GetList extends AsyncTask<Void, Void, List<RowItem>> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Toast.makeText(MainActivity.this, "Json Data is downloading", Toast.LENGTH_LONG).show();
    }


    @Override
    protected List<RowItem> doInBackground(Void... arg0) {
        HttpHandler sh = new HttpHandler();
        // Making a request to url and getting response
        String url = "https://chex-triplebyte.herokuapp.com/api/cats?page=0";
        String jsonStr = sh.makeServiceCall(url);

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

                for (int i = 0; i < list.length(); i++) {
                    JSONObject c = list.getJSONObject(i);
                    String title = c.getString("title");
                    String timestamp = c.getString("timestamp");
                    String image_url = c.getString("image_url");
                    String description = c.getString("description");

                    RowItem item = new RowItem();
                    item.setTitle(title);
                    item.setTimestamp(timestamp);
                    item.setImageUrl(image_url);
                    item.setDescription(description);

                    rowItems.add(item);
                }
            } 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 rowItems;
    }

    @Override
    protected void onPostExecute(List<RowItem> rowItems) {
        super.onPostExecute(rowItems);
        if (rowItems != null) {
            CustomListViewAdapter adapter = new CustomListViewAdapter(MainActivity.this, R.layout.list_item, rowItems);
            listView.setAdapter(adapter);
        }
      }
    }
  }

< Сильный > CustomListViewAdapter.java

public class CustomListViewAdapter extends ArrayAdapter<RowItem> {

private Context context;

public CustomListViewAdapter(Context context, int resourceId,
                             List<RowItem> items) {
    super(context, resourceId, items);
    this.context = context;
}

/*private view holder class*/
private class ViewHolder {
    ImageView imageView;
    TextView txtTitle;
    TextView txtDesc;
}

public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder = null;
    RowItem rowItem = getItem(position);

    LayoutInflater mInflater = (LayoutInflater) context
            .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.list_item, null);
        holder = new ViewHolder();
        holder.txtDesc = (TextView) convertView.findViewById(R.id.description);
        holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
        holder.imageView = (ImageView) convertView.findViewById(R.id.preview);
        convertView.setTag(holder);
    } else
        holder = (ViewHolder) convertView.getTag();

    holder.txtDesc.setText(rowItem.getDescription());
    holder.txtTitle.setText(rowItem.getTitle());
    String url = rowItem.getImageUrl();

    DownloadImageTask downloadImageTask = new DownloadImageTask(holder.imageView);
    downloadImageTask.execute(url);
    return convertView;
}


private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }
 }
}

< Сильный > RowItem.java

public class RowItem {

private String title;
private String timestamp;
private String imageUrl;
private String description;

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getTimestamp() {
    return timestamp;
}

public void setTimestamp(String timestamp) {
    this.timestamp = timestamp;
}

public String getImageUrl() {
    return imageUrl;
}

public void setImageUrl(String imageUrl) {
    this.imageUrl = imageUrl;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}
}

< Сильный > list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/linearLayout2">

<ImageView
    android:id="@+id/preview"
    android:layout_width="80dp"
    android:layout_height="80dp"
    app:srcCompat="@mipmap/ic_launcher"
    android:contentDescription="@string/app_name" />

<TextView
    android:id="@+id/title"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="16dp"
    android:text="@string/app_name"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toEndOf="@+id/preview"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/description"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:text="@string/app_name"
    app:layout_constraintBottom_toBottomOf="@+id/preview"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toEndOf="@+id/preview"
    app:layout_constraintTop_toBottomOf="@+id/title" />
</android.support.constraint.ConstraintLayout>

< Сильный > HttpHandler.java

public class HttpHandler {

private static final String TAG = HttpHandler.class.getSimpleName();

public HttpHandler() {
}

public String makeServiceCall(String reqUrl) {
    String response = null;
    try {
        URL url = new URL(reqUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        // read the response
        InputStream in = new BufferedInputStream(conn.getInputStream());
        response = convertStreamToString(in);
    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(TAG, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }
    return response;
}

private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line).append('\n');
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return sb.toString();
}
 }

< Сильный > activity_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<ListView
    android:id="@+id/item_list"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</LinearLayout>

Примечание:

  1. В item_list.xml реализована ConstraintLayout.

Результат:

Result

1
Silambarasan Poonguti 11 Сен 2017 в 06:08