0

I have an app i'm working on, comprising of 3 Activities. The First 2 Activities work fine. the issue comes up when the third activity is called from a list view(which is generated from a class that extends ASyncTask and a list adapter) in the second activity

The code for the third activity below

package com.dozie.destiny.usda;

import android.app.ProgressDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.multidex.MultiDex;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;

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

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Detailed extends AppCompatActivity {

boolean connected = false;

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

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

        String id= getIntent().getStringExtra("id");
        getarticle GetArticle = new getarticle();
        GetArticle.execute(new String[]{"https://api.nal.usda.gov/pubag/rest/articles/"+"60609"+"/?api_key=DEMO_KEY"});

    }

    public void toaster(String message){
        Toast.makeText(Detailed.this, message, Toast.LENGTH_LONG).show();
    }
     public void networkcheck() {

         ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
         if (connectivityManager.getNetworkInfo(connectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED) {
             connected = true;
         }
         if (connectivityManager.getNetworkInfo(connectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
             connected = true;

         }
     }





    private class getarticle extends AsyncTask<String, Void, String> {

        private ProgressDialog pDialog;
        List<String> authorname = new ArrayList<>();

        //this method is called before download starts. we can display a 'loading' status here
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = new ProgressDialog(Detailed.this);
            pDialog.setMessage("Loading Details...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        protected String doInBackground(String... urls) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(urls[0]).build();

            try {
                Response response = client.newCall(request).execute();
                if (response.isSuccessful()) {
                    return response.body().string();
                }

            } catch (IOException e) {
                e.printStackTrace();
                String message = "Unable to Load Details from Database";
                toaster(message);
                return message;

            }

            String message = "Unable to Load Details from Database";
            toaster(message);
            return message;

        }




        protected void onPostExecute(String result) {

            try {
                JSONObject MyJsonObject = new JSONObject(result);
                JSONArray ResultArray = MyJsonObject.getJSONArray("authors");


                for (int i = 0; i < ResultArray.length(); i++) {
                    JSONObject ResultObject = (JSONObject) ResultArray.get(i); // accessing each item in the array

                   authorname.add(ResultObject.toString()+"\n");

                }
                String title = MyJsonObject.getString("title");
                String source = MyJsonObject.getString("source");
                String abstracts = MyJsonObject.getString("abstract");
                String url = MyJsonObject.getString("url");


                TextView titled = (TextView) findViewById(R.id.titledetail);
                TextView authord = (TextView) findViewById(R.id.authorsdetail);
                TextView abstractd = (TextView) findViewById(R.id.abstractdetail);
                TextView urld = (TextView) findViewById(R.id.linkdetail);
                TextView sourced = (TextView) findViewById(R.id.sourcedetail);

                titled.setText(title);
                authord.setText(authorname.toString());
                abstractd.setText(abstracts);
                sourced.setText(source);
                urld.setText(url);



            } catch (JSONException e) {
                e.printStackTrace();
                String message = "An error occurred while loading data from database";
                toaster(message);
            }
        }
    }
}

The Layout file below

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_detailed"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.dozie.destiny.usda.Detailed">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <ImageView
            android:padding="5dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:src="@drawable/logo1"/>


        <TextView
            android:id="@+id/titledetail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fontFamily="sans-serif-condensed"
            android:text="This is the title"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/authorsdetail"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/abstractdetail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />


        <TextView
            android:id="@+id/sourcedetail"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
           android:text="LINK"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />


        <TextView
            android:id="@+id/linkdetail"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textStyle="italic"
            android:clickable="true"
            android:onClick="linkclicked"/>



    </LinearLayout>

</ScrollView>

My Logcat below

08/10 14:43:36: Launching app
No apk changes detected since last installation, skipping installation of C:\Users\Destiny\AndroidStudioProjects\USDA\app\build\outputs\apk\app-debug.apk
$ adb shell am force-stop com.dozie.destiny.usda
$ adb shell am start -n "com.dozie.destiny.usda/com.dozie.destiny.usda.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 7251 on device emulator-5554
W/dalvikvm: VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
I/dalvikvm: Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.view.WindowCallbackWrapper.onSearchRequested
W/dalvikvm: VFY: unable to resolve interface method 15984: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
D/dalvikvm: VFY: replacing opcode 0x72 at 0x0006
I/dalvikvm: Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.view.WindowCallbackWrapper.onWindowStartingActionMode
W/dalvikvm: VFY: unable to resolve interface method 15988: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
D/dalvikvm: VFY: replacing opcode 0x72 at 0x0008
I/dalvikvm: Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.widget.TintTypedArray.getChangingConfigurations
W/dalvikvm: VFY: unable to resolve virtual method 454: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
D/dalvikvm: VFY: replacing opcode 0x6e at 0x0004
I/dalvikvm: Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.widget.TintTypedArray.getType
W/dalvikvm: VFY: unable to resolve virtual method 476: Landroid/content/res/TypedArray;.getType (I)I
D/dalvikvm: VFY: replacing opcode 0x6e at 0x0006
I/dalvikvm: Could not find method android.content.res.Resources.getDrawable, referenced from method android.support.v7.widget.ResourcesWrapper.getDrawable
W/dalvikvm: VFY: unable to resolve virtual method 417: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
D/dalvikvm: VFY: replacing opcode 0x6e at 0x0008
I/dalvikvm: Could not find method android.content.res.Resources.getDrawableForDensity, referenced from method android.support.v7.widget.ResourcesWrapper.getDrawableForDensity
W/dalvikvm: VFY: unable to resolve virtual method 419: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
D/dalvikvm: VFY: replacing opcode 0x6e at 0x000a
D/dalvikvm: GC_FOR_ALLOC freed 181K, 19% free 3117K/3828K, paused 0ms, total 0ms
I/PGA: Attempting to create new SOCKET connectionn pid = 7251, tid = 7251
I/PGA: New SOCKET connection: com.dozie.destiny.usda (pid 7251, tid 7251)
I/Choreographer: Skipped 31 frames!  The application may be doing too much work on its main thread.
W/dalvikvm: VFY: unable to find class referenced in signature (Ljava/nio/file/Path;)
W/dalvikvm: VFY: unable to find class referenced in signature ([Ljava/nio/file/OpenOption;)
I/dalvikvm: Could not find method java.nio.file.Files.newOutputStream, referenced from method okio.Okio.sink
W/dalvikvm: VFY: unable to resolve static method 22313: Ljava/nio/file/Files;.newOutputStream (Ljava/nio/file/Path;[Ljava/nio/file/OpenOption;)Ljava/io/OutputStream;
D/dalvikvm: VFY: replacing opcode 0x71 at 0x0012
W/dalvikvm: VFY: unable to find class referenced in signature (Ljava/nio/file/Path;)
W/dalvikvm: VFY: unable to find class referenced in signature ([Ljava/nio/file/OpenOption;)
I/dalvikvm: Could not find method java.nio.file.Files.newInputStream, referenced from method okio.Okio.source
W/dalvikvm: VFY: unable to resolve static method 22312: Ljava/nio/file/Files;.newInputStream (Ljava/nio/file/Path;[Ljava/nio/file/OpenOption;)Ljava/io/InputStream;
D/dalvikvm: VFY: replacing opcode 0x71 at 0x0012
I/Choreographer: Skipped 30 frames!  The application may be doing too much work on its main thread.
D/dalvikvm: GC_FOR_ALLOC freed 433K, 12% free 3562K/4028K, paused 30ms, total 30ms
I/MultiDex: VM with version 1.6.0 does not have multidex support
I/MultiDex: install
I/MultiDex: MultiDexExtractor.load(/data/app/com.dozie.destiny.usda-1.apk, false)
I/MultiDex: loading existing secondary dex files
I/MultiDex: load found 0 secondary dex files
I/MultiDex: install done
D/AndroidRuntime: Shutting down VM
W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x95d97b20)
I/Process: Sending signal. PID: 7251 SIG: 9
D/AndroidRuntime: procName from cmdline: com.dozie.destiny.usda
E/AndroidRuntime: in writeCrashedAppName, pkgName :com.dozie.destiny.usda
D/AndroidRuntime: file written successfully with content: com.dozie.destiny.usda StringBuffer : ;com.dozie.destiny.usda
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.dozie.destiny.usda, PID: 7251
                  java.lang.ClassCastException: java.lang.String cannot be cast to org.json.JSONObject
                      at com.dozie.destiny.usda.Detailed$getarticle.onPostExecute(Detailed.java:117)
                      at com.dozie.destiny.usda.Detailed$getarticle.onPostExecute(Detailed.java:66)
                      at android.os.AsyncTask.finish(AsyncTask.java:632)
Application terminated.

Guys, I really need your help, i'm stuck

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

2 Answers2

0

You are trying to cast a String to a JSONObject on JSONObject ResultObject = (JSONObject) ResultArray.get(i); since ResultArray.get(i) returns a String. However, this is not possible.

Try this inside onPostExecute:

for (int i = 0; i < ResultArray.length(); i++) {
                JSONObject ResultObject = ResultArray.getJSONObject(i); // accessing each item in the array

               authorname.add(ResultObject.toString()+"\n");

            }
Ishita Sinha
  • 2,168
  • 4
  • 25
  • 38
0
for (int i = 0; i < ResultArray.length(); i++) {
                JSONObject ResultObject = ResultArray.getJSONObject(i); // accessing each item in the array

               authorname.add(ResultObject.toString()+"\n");

            }

I just realized that i misconstrued a String Array for an Object Array in the JSON data Stream. It was supposed to be

 for (int i = 0; i < ResultArray.length(); i++) {
                    String ResultObject = (String) ResultArray.get(i); // accessing each item in the array

                   authorname.add(ResultObject.toString()+"\n");

                }

A copy of what the JSON Stream looks like below

{  
   "version":"2.0",
   "id":"60609",
   "agid":"60609",
   "title":"Properties of extruded chia - corn meal puffs",
   "authors":[  
      "Jeffrey A Byars",
      "Mukti Singh"
   ],
   "source":"LWT - food science and technology 2015 v.62 no.1, Part 2 pp. 506-510",
   "subjects":[  
      "corn meal",
      "energy",
      "extrusion",
      "fatty acids",
      "food processing",
      "grinding",
      "hardness",
      "heat",
      "seeds",
      "temperature",
      "water content"
   ],
   "url":"http://dx.doi.org/10.1016/j.lwt.2014.06.036",
   "abstract":"This study investigated the properties of extruded corn meal puffs containing chia. Mixtures of corn meal and chia seeds (0-20 g/100 g) were processed in a laboratory-scale twin-screw extruder at different moisture contents (18-22 g/100 g) and final heating zone temperatures (120-160°C). Extrusion processing provides a simple method for grinding the seeds, which is necessary for making the fatty acids available. The expansion of cylindrical extrudates decreased with increasing chia content, increasing moisture and increasing final heating zone temperature. The hardness of the extrudates increased with increasing moisture content and decreased at intermediate chia levels. The specific mechanical energy of the extrusion process decreased with increasing chia content."
}

Thanks to everyone for their responses, i really do appreciate it