2016-12-21 18 views
-2

私はリストビューを表示するアプリケーションを開発していますが、実行時エラー これは私のコードです。実行時にコードファイルと例外エラーがあります。このエラーがなぜ発生するのか致命的な例外:AsyncTask#1

package com.example.official2.xoxo.activity; 

import android.app.ProgressDialog; 
import android.content.Intent; 
import android.graphics.Bitmap; 
import android.os.AsyncTask; 
import android.os.Bundle; 
import android.support.v7.app.AppCompatActivity; 
import android.util.Log; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.ArrayAdapter; 
import android.widget.ListAdapter; 
import android.widget.ListView; 
import android.widget.SimpleAdapter; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.example.official2.xoxo.R; 
import com.example.official2.xoxo.app.Config; 

import com.example.official2.xoxo.helper.JSONParser; 
import com.example.official2.xoxo.helper.JsonWebToken; 
import com.example.official2.xoxo.helper.SQLiteHandler; 
import com.example.official2.xoxo.helper.ServiceHandler; 

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

import java.util.ArrayList; 
import java.util.HashMap; 
public class Products extends AppCompatActivity{ 

private String TAG = Products.class.getSimpleName(); 
//Call the config class to get the url 
public Config con = new Config(); 
private String url_details = con.getAllProducts(); 

//ArrayOption-->Array Adapter--> ListView 
//List View:(Views: productlist.xml) 
private ListView lv; 
private ProgressDialog pDialog; 
    // CustomListAdapter adapter; 
    JSONParser jsonParser = new JSONParser(); 
    ServiceHandler sh; 
    ArrayList<HashMap<String, String>> productList; 
// URL to get contacts JSON 
private static String url = "http://uat.fxhello.com/api/shop/products"; 
JsonWebToken jsonWebToken; 
//JSON NODE NAMES 
private static final String TAG_SUCCESS = "success"; 
private static final String TAG_PRODUCT = "payload"; 
private static final String TAG_ID = "id"; 
private static final String TAG_NAME = "product_name"; 
private static final String TAG_PRICE = "price"; 
private static final String TAG_PIC = "profileimage"; 

private SQLiteHandler db; 
JSONArray contacts = null; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_products); 
    productList = new ArrayList<>(); 

    lv = (ListView) findViewById(R.id.listViewProducts); 

    jsonWebToken = new JsonWebToken(); 
    // String tok = jsonWebToken.getDefaults(getContext()); 
    String tok = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjE3MDcsImlzcyI6Imh0dHA6XC9cL3VhdC5meGhlbGxvLmNvbVwvYXBpXC9hdXRoZW50aWNhdGUiLCJpYXQiOjE0ODIzNDMzMDMsImV4cCI6MTQ4MjQyOTcwMywibmJmIjoxNDgyMzQzMzAzLCJqdGkiOiI3NGQ5ZGIwNTA3NDc2NDAwNzc2MmYzODJiNGQxZmU4MCJ9.LF2Q8KUD7hoFjBJ4fsNjYS8rCzCevsZ4g0jukBK0lj0"; 
    Log.d("Responsetoken", tok); 

    new Getproduct().execute(); 

    //populateListView(); 
} 
/** 
* Async task class to get json by making HTTP call 
*/ 
private class Getproduct extends AsyncTask<String, Void, JSONObject> { 
    private JSONObject json; 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     // Showing progress dialog 
     // pDialog = new ProgressDialog(Products.this); 
     //pDialog.setMessage("Loading Contacts. Please wait..."); 
     //pDialog.setIndeterminate(false); 
     //pDialog.setCancelable(false); 
     //pDialog.show(); 
    } 

    protected JSONObject doInBackground(String... args) { 

     String userID = args[0]; 
     sh = new ServiceHandler(userID); 

     String jsondata = sh.makeServiceCall(url_details, ServiceHandler.POST, null); 
     // JSONObject json = jsonParser.makeHttpRequest(url_details,"GET"); 
     System.out.println("jsondata" + jsondata); 
     if (jsondata != null) 
      Log.d("Create Response", jsondata); 
     else { 

      Toast.makeText(Products.this.getApplicationContext(), "Connection fail", Toast.LENGTH_SHORT).show(); 
     } 
     try { 
      json = new JSONObject(jsondata); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 


     return json; 
    } 

    @Override 
    protected void onPostExecute(JSONObject s) { 
     // dismiss the dialog after getting all products 
     // pDialog.dismiss(); 

     System.out.println(productList); 

     try { 

      JSONArray products = json.getJSONArray(TAG_PRODUCT); 

      for (int i = 0; i < contacts.length(); i++) { 
       JSONObject c = contacts.getJSONObject(i); 

       //Storing each json item in a variable 
       String id = c.getString(TAG_ID); 
       String name = c.getString(TAG_NAME); 
       String price = c.getString(TAG_PRICE); 
       // String image = c.getString(TAG_PIC); 
       //tmp hash map for single contact 
       HashMap<String, String> map = new HashMap<String, String>(); 

       //adding each child node to HashMap => value 
       map.put(TAG_ID, id); 
       map.put(TAG_NAME, name); 
       map.put(TAG_PRICE, price); 
       // map.put(TAG_PIC,image); 
       productList.add(map); 
       // adding contact to contact list 
       productList.add(map); 

       // Dismiss the progress dialog 
       //if (pDialog.isShowing()) 
        // pDialog.dismiss(); 

       ListAdapter adapter = new SimpleAdapter(
         Products.this, productList, 
         R.layout.productlist, new String[]{TAG_ID, TAG_NAME, 
         TAG_PRICE}, new int[]{R.id.name, 
         R.id.email, R.id.mobile}); 

       lv.setAdapter(adapter); 
      } 
     } 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(); 
       } 
      }); 

     } 
    } 
} 

} 

ServiceHandlerクラスファイル。私は-------------私は

FATAL EXCEPTION: AsyncTask #1 
Process: com.example.official2.xoxo, PID: 30695 
java.lang.RuntimeException: An error occurred while executing doInBackground() 
    at android.os.AsyncTask$3.done(AsyncTask.java:309) 
    at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354) 
    at java.util.concurrent.FutureTask.setException(FutureTask.java:223) 
    at java.util.concurrent.FutureTask.run(FutureTask.java:242) 
    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) 
    at java.lang.Thread.run(Thread.java:818) 
    Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0 
    at com.example.official2.xoxo.activity.Products$Getproduct.doInBackground(Products.java:97) 
    at com.example.official2.xoxo.activity.Products$Getproduct.doInBackground(Products.java:95) 
    at android.os.AsyncTask$2.call(AsyncTask.java:295) 
    at java.util.concurrent.FutureTask.run(FutureTask.java:237) 

これは、サーバー側の値であり、これをエラーとして得た

package com.example.official2.xoxo.helper; 

import android.util.Log; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.utils.URLEncodedUtils; 
import org.apache.http.impl.client.DefaultHttpClient; 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.io.UnsupportedEncodingException; 
import java.util.List; 

/** 
* Created by Official 2 on 12/19/2016. 
*/ 
public class ServiceHandler { 

static InputStream is = null; 
static String response = null; 
public final static int GET = 1; 
public final static int POST = 2; 
private String token; 
private String refresh_url = "application/vnd.fxhello.v1+json"; 

public ServiceHandler() { 

} 

public ServiceHandler(String token) { 
    this.token = token; 
} 

/** 
* Making service call 
* @url - url to make request 
* @method - http request method 
* */ 
/** 
* Making service call 
* @url - url to make request 
* @method - http request method 
* @params - http request params 
* */ 
public String makeServiceCall(String url, int method, 
           List<NameValuePair> params) { 
    try { 

     // http client 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpEntity httpEntity = null; 
     HttpResponse httpResponse = null; 

     // Checking http request method type 
     if (method == POST) { 
      HttpPost httpPost = new HttpPost(url); 
      // adding post params 
      if (params != null) { 
       httpPost.setEntity(new UrlEncodedFormEntity(params)); 
      } 

      httpResponse = httpClient.execute(httpPost); 

     } else if (method == GET) { 
      // appending params to url 
      String tok = token; 
      Log.d("Responsetoken", tok); 
      if (params != null) { 
       String paramString = URLEncodedUtils 
         .format(params, "utf-8"); 
       url += "?" + paramString; 
      } 
      HttpGet httpGet = new HttpGet(url); 
      httpGet.setHeader("Authorization","Bearer "+tok); 
      httpGet.setHeader("Accept", refresh_url); 
      httpResponse = httpClient.execute(httpGet); 

     } 
     httpEntity = httpResponse.getEntity(); 
     is = httpEntity.getContent(); 

    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "UTF-8"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     is.close(); 
     response = sb.toString(); 
    } catch (Exception e) { 
     Log.e("Buffer Error", "Error: " + e.toString()); 
    } 

    return response; 

} 

public String makeADDCall(String url, int method, 


          List<NameValuePair> params) { 
    try { 

     // http client 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpEntity httpEntity = null; 
     HttpResponse httpResponse = null; 

     // Checking http request method type 
     if (method == POST) { 
      String tok = token; 
      HttpPost httpPost = new HttpPost(url); 
      // adding post params 
      if (params != null) { 
       httpPost.setEntity(new UrlEncodedFormEntity(params)); 
       httpPost.setHeader("Authorization","Bearer "+tok); 
       httpPost.setHeader("Accept", refresh_url); 
      } 

      httpResponse = httpClient.execute(httpPost); 

     } else if (method == GET) { 
      // appending params to url 
      String tok = token; 
      Log.d("Responsetoken", tok); 
      if (params != null) { 
       String paramString = URLEncodedUtils 
         .format(params, "utf-8"); 
       url += "?" + paramString; 
      } 
      HttpGet httpGet = new HttpGet(url); 
      httpGet.setHeader("Authorization",tok); 
      httpGet.setHeader("Accept", refresh_url); 
      httpResponse = httpClient.execute(httpGet); 

     } 
     httpEntity = httpResponse.getEntity(); 
     is = httpEntity.getContent(); 

    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
       is, "UTF-8"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     is.close(); 
     response = sb.toString(); 
    } catch (Exception e) { 
     Log.e("Buffer Error", "Error: " + e.toString()); 
    } 

    return response; 

} 

    } 

サービスハンドラからの製品にデータを取得するには、このコードを使用しました--------------

enter image description here

+0

スタックトレースを読み込みます。それは 'String userID = args [0]; 'を指しています;あなたはどんな価値があると思いますか? – njzk2

+0

サービスハンドラクラス – Gayan

+0

からProducts.javaの 'ArrayIndexOutOfBoundsException'のデータを渡すために使用されました。 –

答えて

0

連絡先JsonArrayはnullです。

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

JSONArray products = json.getJSONArray(TAG_PRODUCT) 
     for (int i = 0; i < products.length(); i++) {} 
+0

番号。エラーをもう一度読んでください。 – njzk2

+0

はい@ njzk2に同意し、引数がnullと思われます。 – Rahul

+0

私はラフルを訂正しました。しかし、同じエラーが実際には – Gayan

0

にする必要があり、私はこの方法であなたはUIスレッドと通信できないので... PreExecuteとPostExecute方法を行うことができます... doInBackgroundメソッドでトーストが問題を引き起こしていると思います。

+0

番号。エラーをもう一度読んでください。 – njzk2

+0

ohhはい... for forループのcontants.length()の代わりにcontacts.length()-1を書く –

+0

何?いいえ、それはインデックスの仕組みではありません。 – njzk2

0

へのあなたのスタックトレースリンク:

この行に対応する
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0 
    at com.example.official2.xoxo.activity.Products$Getproduct.doInBackground(Products.java:97) 
    at com.example.official2.xoxo.activity.Products$Getproduct.doInBackground(Products.java:95) 

は:String userID = args[0];

この行は、ArrayIndexOutOfBoundsExceptionが

を説明する配列で、そして、それはこのためです:

new Getproduct().execute(); 

あなたは決していかなるアルムーマンも渡しませんtsでgetproductを初期化すると、配列インデックスが0になり、例外が発生します。

関連する問題