变量在asynctask android .null指针异常

时间:2016-12-25 00:22:40

标签: android listview android-asynctask android-arrayadapter

我试图连接我的应用程序从数据库查询获取信息执行写入和变量放置。但是当它从fn doinbackground终止时,我发现变量有变量为null,它关闭整个程序。我注意到,当doinbackgroundfn中的try块返回结果时,它会跳转到fn结束时返回,然后app停止。 这是主要的代码 Bur如何执行查询并打印制作适配器? 主要代码

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

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

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

public class choose_buffet_items extends AppCompatActivity {
    String []categouries;
    ArrayList<buffetcategories> buff_list = new ArrayList<buffetcategories>();
    buffetcatadapter itemsAdapter;

    ArrayAdapter adapter;
    private static int SPLASH_TIME_OUT=2000;
    AlertDialog alertDialog;
    private boolean loggedIn = false;
    String type;
    String result;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choose_buffet_items);

        new JSONParse().execute();

            itemsAdapter = new buffetcatadapter(this, buff_list);
             itemsAdapter.notifyDataSetChanged();

            ListView listView = (ListView) findViewById(R.id.listView_buffet);
            listView.setAdapter(itemsAdapter);

            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    String s =(String)adapter.getItem(i);
                    if(s.equals("Drinks"))
                    {
                        Intent numbersIntent = new Intent(choose_buffet_items.this, buffet_drinks.class);
                        startActivity(numbersIntent);
                    }
                    else if(s.equals("Cakes"))
                    {
                        Intent numbersIntent = new Intent(choose_buffet_items.this, buffet_cake.class);
                        startActivity(numbersIntent);
                    }
                    else if(s.equals("Appetizers"))
                    {
                        Intent numbersIntent = new Intent(choose_buffet_items.this,buffet_appetizers.class);
                        startActivity(numbersIntent);
                    }
                    else {Intent numbersIntent = new Intent(choose_buffet_items.this, buffet_lunch.class);
                        startActivity(numbersIntent);}

                }
            });


            listView.setAdapter(adapter);



    }
    private class JSONParse extends AsyncTask<String, String, String> {
        private ProgressDialog pDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            alertDialog=new AlertDialog.Builder(choose_buffet_items.this).create();
            alertDialog.setTitle("Upadting Data");
            pDialog = new ProgressDialog(choose_buffet_items.this);
            pDialog.setMessage("Getting Data ...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();


        }


        @Override
        protected String doInBackground(String... args) {



                String login_URL = "http://2f179dfb.ngrok.io/getcat.php";
                try {

                    //Fetching the boolean value form sharedpreferences


                    URL url = new URL(login_URL);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("POST");
                    httpURLConnection.setDoOutput(true);
                    httpURLConnection.setDoInput(true);

                    InputStream inputStream = httpURLConnection.getInputStream();
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
                    result = "";
                    String line = "";
                    while ((line = bufferedReader.readLine()) != null) {
                        result += line;
                    }
                    bufferedReader.close();
                    inputStream.close();
                    httpURLConnection.disconnect();
                    Log.e("RESULT", result);
                    JSONObject jsonObject = new JSONObject(result);

                    JSONArray result1 = jsonObject.getJSONArray("result");
                    //categouries=new String[result1.length()];
                    for (int i = 0; i < result1.length(); i++) {
                        JSONObject c = result1.getJSONObject(i);
                        String category = c.getString("buffCategory");
                        buff_list.add(new buffetcategories(category));


                    }

                    return result;


                }
                catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return result;
            }




        @Override
        protected void onPostExecute(String r) {
               itemsAdapter.notifyDataSetChanged();
               pDialog.dismiss();
            alertDialog.setMessage("hello");
            alertDialog.show();




        }
    }


}

这是适配器代码

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

import java.util.ArrayList;

/**
 * Created by extra on 25/12/2016.
 */
public class buffetcatadapter  extends ArrayAdapter<buffetcategories> {
    Context context;
    ArrayList<buffetcategories> items;
    public buffetcatadapter(Activity context, ArrayList<buffetcategories> buffitems) {
        // Here, we initialize the ArrayAdapter's internal storage for the context and the list.
        // the second argument is used when the ArrayAdapter is populating a single TextView.
        // Because this is a custom adapter for two TextViews and an ImageView, the adapter is not
        // going to use this second argument, so it can be any value. Here, we used 0.
        super(context, 0,buffitems);
        this.context=context;
        this.items=buffitems;
    }


    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        // Check if the existing view is being reused, otherwise inflate the view
        View listItemView = convertView;
        if (listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.listviewbuffetcat, parent, false);

        }

        // Get the {@link AndroidFlavor} object located at this position in the list
        final buffetcategories currentAndroidFlavor = getItem(position);

        // Find the TextView in the list_item.xml layout with the ID version_name
        TextView nameTextView = (TextView) listItemView.findViewById(R.id.categouries);

        // Get the version name from the current AndroidFlavor object and
        // set this text on the name TextView
        nameTextView.setText(currentAndroidFlavor.getCategouries());
        Log.e("hhhh", nameTextView.getText().toString());

        // Find the TextView in the list_item.xml layout with the ID version_number
        ;
        // Return the whole list item layout (containing 2 TextViews and an ImageView)
        // so that it can be shown in the ListView
        return listItemView;
    }

    @Override
    public int getCount() {
        if(items == null)
            return 0;
        return items.size();
    }

    @Override
    public buffetcategories getItem(int i) {
        return items.get(i);
    }
}

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"
    android:minHeight="@dimen/list_item_height"
    android:padding="16dp"
    android:background="#bbe0f7">
    <ListView

        android:id="@+id/listView_buffet"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

    </ListView>

</LinearLayout>

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"
    android:minHeight="88dp">
    <TextView
        android:id="@+id/categouries"
        android:layout_height="wrap_content"
        android:textAppearance="?android:textAppearanceMedium"
        android:layout_width="wrap_content"
        android:text="name"


        />

</LinearLayout>

log cat

com.rematchka.weddinghall E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: com.rematchka.weddinghall, PID: 27828
                                                                           java.lang.RuntimeException: Unable to start activity ComponentInfo{com.rematchka.weddinghall/com.rematchka.weddinghall.choose_buffet_items}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                                                                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                               at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                               at android.os.Looper.loop(Looper.java:148)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                            Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
                                                                               at com.rematchka.weddinghall.choose_buffet_items.onCreate(choose_buffet_items.java:58)
                                                                               at android.app.Activity.performCreate(Activity.java:6237)
                                                                               at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                               at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                               at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                                                                               at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                                                                               at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                               at android.os.Looper.loop(Looper.java:148) 
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                                               at java.lang.reflect.Method.invoke(Native Method) 
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
12-25 02:33:15.908 27828-29079/com.rematchka.weddinghall E/RESULT: {"result":[{"buffCategory":"Drinks"},{"buffCategory":"Cakes"},{"buffCategory":"Appetizers"},{"buffCategory":"Lunch"}]}

1 个答案:

答案 0 :(得分:0)

您获得NullPointerException的原因是,当您致电<?PHP $now = new DateTime; $now->modify('-1 years'); //or +1 or +5 years echo $now->format('Y'); //and here again For 4 digit ('Y') for 2 digit ('y') ?> 时,您尚未初始化listView.setAdapter(adapter);。此外,adapter可能会给您一个类似的例外。你的意思是写String s =(String)adapter.getItem(i);吗?