数据发送到活动的接口崩溃

Posted

技术标签:

【中文标题】数据发送到活动的接口崩溃【英文标题】:Crash on Interface on data send to activity 【发布时间】:2017-08-16 21:31:45 【问题描述】:

我有一个将执行 asynctask 的主要活动,然后使用接口将数据发送回活动,如下面的代码所示

主要活动

 protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile_scroll);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    String type = "getProfile";

    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
    SharedPreferences.Editor editor = pref.edit();
    String username = pref.getString("username", null);

    RetrieveData retrieveData = new RetrieveData(this);

    retrieveData.execute(type,username);


public void sendData(String response) 
    // TODO Auto-generated method stub
    String name="";
    String age="";
    String gender = "";
    String id = "";
    try 
        JSONObject jsonObject = new JSONObject(response);
        JSONArray result = jsonObject.getJSONArray("result");
        JSONObject collegeData = result.getJSONObject(0);
        ImageView imageView = (ImageView) findViewById(R.id.imageView2);

        name = collegeData.getString("name");
        age = collegeData.getString("age");
        gender = collegeData.getString("gender");
        id = collegeData.getString("id");
        EditText MyName = (EditText) findViewById(R.id.editText14);
        MyName.setText(name);
        EditText MyAge = (EditText) findViewById(R.id.editText21);
        MyAge.setText(age);
        EditText MyGender = (EditText) findViewById(R.id.editText22);
        MyGender.setText(gender);
        Picasso.with(this).load("http://192.168.12.252/"+id+"/profile.png").memoryPolicy(MemoryPolicy.NO_CACHE).networkPolicy(NetworkPolicy.NO_CACHE).into(imageView);
     catch (JSONException e) 
        e.printStackTrace();
    

异步任务

public class RetrieveData extends AsyncTask<String,Void,String>
    Context context;
    RetrieveData(Context ctx) 
        context = ctx;
    
    private OnDataSendToActivity dataSendToActivity;

    public RetrieveData(View.OnClickListener activity)
        dataSendToActivity = (OnDataSendToActivity)activity;
    

    @Override
    protected String doInBackground(String... params) 
        String profile_url = "http://192.168.12.252/getprofile.php";
        String image_url = "http://192.168.12.252/imagelist.php";
        String type = params[0];

        if(type.equals("getProfile"))
            try 
                String user_name = params[1];
                URL url = new URL(profile_url);
                HttpURLConnection httpURLConnection = null;
                httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);

                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                String post_data = URLEncoder.encode("user_name", "UTF-8")+"="+URLEncoder.encode(user_name, "UTF-8");
                bufferedWriter.write(post_data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();

                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String result = null;
                result = bufferedReader.readLine();
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return result;
             catch (IOException e) 
                e.printStackTrace();
            
        else if(type.equals("getProfileImages"))
            try 
                String user_name = params[1];
                URL url = new URL(image_url);
                HttpURLConnection httpURLConnection = null;
                httpURLConnection = (HttpURLConnection)url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);

                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                String post_data = URLEncoder.encode("Image", "UTF-8")+"="+URLEncoder.encode("Image", "UTF-8")+"&"+URLEncoder.encode("user_name", "UTF-8")+"="+URLEncoder.encode(user_name, "UTF-8");
                bufferedWriter.write(post_data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();

                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String result = null;
                result = bufferedReader.readLine();
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return result;
             catch (IOException e) 
                e.printStackTrace();
            
        
        return null;
    

    @Override
    protected void onPostExecute(String result) 
        super.onPostExecute(result);
        dataSendToActivity.sendData(result);
    

界面

public interface OnDataSendToActivity 
    void sendData(String str);

当我执行代码时,它在这一行崩溃

dataSendToActivity.sendData(result);

android 监视器中的错误如下所示,我不明白是什么问题

    --------- beginning of crash
03-24 04:12:42.518 20964-20964/com.example.lenovo.maidfriends E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.lenovo.maidfriends, PID: 20964
                                                                                java.lang.NullPointerException: Attempt to invoke interface method 'void com.example.lenovo.maidfriends.OnDataSendToActivity.sendData(java.lang.String)' on a null object reference
                                                                                    at com.example.lenovo.maidfriends.RetrieveData.onPostExecute(RetrieveData.java:119)
                                                                                    at com.example.lenovo.maidfriends.RetrieveData.onPostExecute(RetrieveData.java:33)
                                                                                    at android.os.AsyncTask.finish(AsyncTask.java:667)
                                                                                    at android.os.AsyncTask.-wrap1(AsyncTask.java)
                                                                                    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:684)
                                                                                    at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                    at android.os.Looper.loop(Looper.java:154)
                                                                                    at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                    at java.lang.reflect.Method.invoke(Native Method)
                                                                                    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

我假设它说,结果中没有任何价值,但事实并非如此,结果中有一些东西。

谁能告诉我怎么了?

【问题讨论】:

你有没有初始化 dataSendToActivity 变量。 @santoshgore 你的意思是在异步任务中?我已经编辑了代码,你能帮我再看一遍吗 你的 sendMyData() 方法在哪里?当你调用 sendMyData 时,你调用的对象为空。 @santoshgore 抱歉我贴错了,请再看一下我的错误信息 好的。 dataSendToActivity 为空。所以请验证是否调用了 RetrieveData 构造函数?因为您正在构造函数中设置 dataSendToActivity 的值。 【参考方案1】:

您没有覆盖 Main Activity 中的 RetrieveData 函数。您只是在创建一个具有相同名称的新函数。

而不是将 Asynctask 称为:

RetrieveData retrieveData = new RetrieveData(this);

使用以下代码:

RetrieveData retrieveData = new RetrieveData(new RetrieveData()
public void sendData(String response) 
    // TODO Auto-generated method stub
    String name="";
    String age="";
    String gender = "";
    String id = "";
    try 
        JSONObject jsonObject = new JSONObject(response);
        JSONArray result = jsonObject.getJSONArray("result");
        JSONObject collegeData = result.getJSONObject(0);
        ImageView imageView = (ImageView) findViewById(R.id.imageView2);

        name = collegeData.getString("name");
        age = collegeData.getString("age");
        gender = collegeData.getString("gender");
        id = collegeData.getString("id");
        EditText MyName = (EditText) findViewById(R.id.editText14);
        MyName.setText(name);`enter code here`
        EditText MyAge = (EditText) findViewById(R.id.editText21);
        MyAge.setText(age);
        EditText MyGender = (EditText) findViewById(R.id.editText22);
        MyGender.setText(gender);
        Picasso.with(this).load("http://192.168.12.252/"+id+"/profile.png").memoryPolicy(MemoryPolicy.NO_CACHE).networkPolicy(NetworkPolicy.NO_CACHE).into(imageView);
     catch (JSONException e) 
        e.printStackTrace();
    

);

移除 Main Activity 的 sendData()

同样在 RetrieveData 类中,替换以下代码:

 public RetrieveData(View.OnClickListener activity)
        dataSendToActivity = (OnDataSendToActivity)activity;
    

与:

public RetrieveData(OnDataSendToActivity activity)
    dataSendToActivity = activity;

如果您遇到任何问题,请告诉我。

【讨论】:

【参考方案2】:

onPostExecute 调用sendData() 很简单:

MainActivity ma=new MainActivity();
ma.sendData(result);

【讨论】:

以上是关于数据发送到活动的接口崩溃的主要内容,如果未能解决你的问题,请参考以下文章

如何通过 Parcelable 接口将 WifiP2pManager 对象发送到另一个活动

无法在后台服务中将数据发送到Firebase

将数据从一个片段发送到另一个片段时出错。 (两个片段都由一个活动托管)

不将数据发送到下一个活动,而是发送到之后的活动(使用 parcelable)

将接口从片段传递到kotlin中的活动

在Android中将数据从活动发送到片段