java - 空数组错误

标签 java android android-asynctask

在我的代码上。

package com.example.onewdivide.fortunecookiesnew;

import android.content.Intent; import android.os.AsyncTask; import
android.support.v7.app.AppCompatActivity; import android.os.Bundle;
import android.util.Log; import android.view.Menu; import
android.view.MenuInflater; import android.view.MenuItem; import
android.view.View; import android.widget.ImageButton; import
android.widget.ImageView; import android.widget.TextView;

import com.google.gson.Gson; import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type; import java.util.Collection;

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

public class Process extends AppCompatActivity {

    ImageButton MakeAWish;
    TextView TextAtB;
    TextView TextAtCookies;
    TextView TextAtDate;
    TextView TextAtResult;
    ImageView Cookies;
    String meanning;
    String[] ResultFromRequest;
    int Check;

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

        MakeAWish = (ImageButton) findViewById(R.id.Button);
        MakeAWish.setOnClickListener(myhandler1);

        TextAtB = (TextView) findViewById(R.id.textatbutton);
        TextAtCookies = (TextView)findViewById(R.id.resultatpic);
        TextAtDate = (TextView)findViewById(R.id.date);
        TextAtResult = (TextView)findViewById(R.id.textView7);

        Cookies = (ImageView)findViewById(R.id.imageView);
        Log.d("Debug this","zero");
        Check = 0;

    }

    public class JSONTask extends AsyncTask<String[], Void, CookiesResponse[]> {

        @Override
        protected CookiesResponse[] doInBackground(String[]... strings) {

            try{
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder().url("www.atilal.info/cookies.php").build();

                Response response = client.newCall(request).execute();
                String result = response.body().string();

                Gson gson = new Gson();

                Type collectionType = new TypeToken<Collection<CookiesResponse>>() {}.getType();
                Collection<CookiesResponse> enums = gson.fromJson(result, collectionType);
                CookiesResponse[] cookiesResult = enums.toArray(new CookiesResponse[enums.size()]);

                String[] resultlast = {cookiesResult[0].getMeaning(),cookiesResult[0].getMessage()};
                Log.d("Debug this","two");
                ResultFromRequest = resultlast;
                return cookiesResult;

            }catch (Exception e){

            }
            return null;
        }

        @Override
        protected void onPostExecute(CookiesResponse[] s){
            super.onPostExecute(s);


        }

    }

    View.OnClickListener myhandler1 = new View.OnClickListener() {
        public void onClick(View v) {
            Check+=1;
            new JSONTask().execute();
            if(Check==1){
                Log.d("Debug this","one");

                TextAtCookies.setText(ResultFromRequest[0]);
                TextAtResult.setText("Result : "+ ResultFromRequest[0]);
                meanning = ResultFromRequest[1];
                TextAtB.setText("SAVE");

            }

        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.mainmenu, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_name) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent); //            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}

当我点击我的按钮时。将会出现致命异常。这就是说

10-25 02:15:05.804 9777-9809/com.example.onewdivide.fortunecookiesnew E/OpenGLRenderer: allen debug liyu Key: 68724719680
10-25 02:15:06.426 9777-9777/com.example.onewdivide.fortunecookiesnew E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.onewdivide.fortunecookiesnew, PID: 9777
    java.lang.NullPointerException: Attempt to read from null array
        at com.example.onewdivide.fortunecookiesnew.Process$1.onClick(Process.java:104)
        at android.view.View.performClick(View.java:5646)
        at android.view.View$PerformClick.run(View.java:22459)
        at android.os.Handler.handleCallback(Handler.java:761)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:156)
        at android.app.ActivityThread.main(ActivityThread.java:6523)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832) 10-25
02:15:06.435 9777-9777/com.example.onewdivide.fortunecookiesnew I/Process: Sending signal. PID: 9777 SIG: 9

最佳答案

您的AsyncTask异步执行,并且您尝试在设置之前读取数组。

将此代码从 OnClickListener 移至方法 onPostExecute:

@Override
protected void onPostExecute(CookiesResponse[] s){
    if(Check==1){
        Log.d("Debug this","one");

        TextAtCookies.setText(ResultFromRequest[0]);
        TextAtResult.setText("Result : "+ ResultFromRequest[0]);
        meanning = ResultFromRequest[1];
        TextAtB.setText("SAVE");

    }
}

该代码将在 AsyncTask 结束后调用。

关于java - 空数组错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46918514/

相关文章:

java - 我有 Spring Boot 应用程序,但出现以下错误

java - Android 异步任务回收位图

java - java按钮java中的空指针异常错误

java - Firebase -(具有多个子节点的 DataSnapshot)- NullPointerException

java - 使用soot比较两个apk文件的调用图

java - 将数据传回 Android Studio 中的先前 Activity

java - 单击通知后不显示警报对话框

android - 在 AsyncTask Android 中获取 JSON

java - 如何在Java中处理JSON(Android Studio)

android - 如何使用android espresso test设置textview的可见性