失败onPostExecute

时间:2014-11-03 03:34:01

标签: java android

我有一个应用程序我试图通过ASYNC任务传递数据但在我的onPosteExecute方法中得到一个空指针错误。似乎无论我如何更改我的代码,我仍然会得到同样的致命错误:

 10-31 18:43:56.517    1253-1253/com.brianstacks.project1 E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.brianstacks.project1, PID: 1253
    java.lang.NullPointerException
            at com.brianstacks.project1.MainActivity$MyTask.onPostExecute(MainActivity.java:277)
            at com.brianstacks.project1.MainActivity$MyTask.onPostExecute(MainActivity.java:247)
            at android.os.AsyncTask.finish(AsyncTask.java:632)
            at android.os.AsyncTask.access$600(AsyncTask.java:177)
            at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5001)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
            at dalvik.system.NativeStart.main(Native Method)

这是我的代码:

MainActivity.java

public class MainActivity extends ListActivity implements MasterFragment.OnListItemClickListener {

    final String Tag = "Project 1 test";
    EditText myEdit;
    Button myButton;
    ProgressBar pb;
    SerialCustomObject myObject;
    // create a reference to the list's needed for data
    List<MyTask> tasks;
    ArrayList<Places>  placeList;

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


        if ((savedInstanceState != null)&& (savedInstanceState.getSerializable("name") != null)) {
        Places name = (Places) savedInstanceState.getSerializable("name");
            Log.v("name:",name.getName());
     }


        //initiate my tasks
        tasks = new ArrayList<>();
        pb = (ProgressBar)findViewById(R.id.progressBar);
        myEdit = (EditText)findViewById(R.id.myEditText);
        myButton = (Button)findViewById(R.id.myButton);

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, 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();
        return id == R.id.action_settings || super.onOptionsItemSelected(item);
    }

    public void findAndRemoveFragment() {
        FragmentManager mgr = getFragmentManager();
        DetailFragment frag =
                (DetailFragment) mgr.findFragmentByTag(DetailFragment.TAG);

        if (frag == null) {
            // No fragment found, possibly because the transaction
            // hasn't completed yet.
        } else {
            // Fragment found. You can use it here.
            FragmentTransaction trans = mgr.beginTransaction();
            trans.remove(frag);
            trans.commit();
            // When the main thread runs, the fragment will be
            // removed from the activity.
        }
    }

    public void deviceStorage() {
        // Read in a private file
        try {
            FileInputStream fis = this.openFileInput("some_file.txt");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // Create new or open existing private file
        try {
            FileOutputStream fos = this.openFileOutput("some_other_file.txt", Context.MODE_PRIVATE);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


    }

    private void writeToFile(Context _c, String _filename, String _data) {
        File external = _c.getExternalFilesDir(null);
        File file = new File(external, _filename);

        try {
            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);

            if(myObject == null) {
                myObject = new SerialCustomObject();
            }
            myObject.setData(_data);

            oos.writeObject(myObject);
            oos.close();
            // Write bytes to the stream
            fos.write(_data.getBytes());

            // Close the stream to save the file.
            fos.close();

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


    private String readFromFile(String _filename) {
        File external = getExternalFilesDir(null);
        File file = new File(external, _filename);

        try {
            FileInputStream fin = new FileInputStream(file);
            InputStreamReader inReader = new InputStreamReader(fin);
            BufferedReader reader = new BufferedReader(inReader);

            // Reading data from our file using the reader
            // and storing it our string buffer.
            StringBuffer buffer = new StringBuffer();
            String text = null;
            // Make sure a line of text is available to be read.
            while((text = reader.readLine()) != null) {
                buffer.append(text + "\n");
            }
            // Close the reader and underlying stream.
            reader.close();
            // Convert the buffer to a string.
            return buffer.toString();
        } catch(IOException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public void displayText(String myText) {

        DetailFragment frag = (DetailFragment) getFragmentManager().findFragmentByTag(DetailFragment.TAG);
        if (frag == null){
            frag = DetailFragment.newInstance(myText);
            getFragmentManager().beginTransaction()
                    .replace(R.id.container2,frag,DetailFragment.TAG)
                    .commit();
        }else {
            frag.setDisplayInfo(myText);
        }
    }

    //@Override
    public void onClick(View _v){

            myEdit = (EditText)findViewById(R.id.myEditText);
            String newString = myEdit.getText().toString();
            Log.v(Tag,newString);
        }

    // the method for when the button is clicked
    public void myClick(View _v){
        // create a string to grab the text of the edit text
        String myString = myEdit.getText().toString();
        // replace the spaces with + to encode into the url
        String encodedString = myString.replace(" ","+");
        //check to see if online and if so continue to get the JSON data if not toast a message telling the user no connection
        if (isOnline()){
            requestData("https://maps.googleapis.com/maps/api/place/textsearch/json?query="+encodedString+"&key=AIzaSyB9iOw6wF4FwbOdUTZYiU_MxsbfWM5iMOI");
        }else Toast.makeText(this, "Network isn't available", Toast.LENGTH_SHORT).show();

    }

    // method to get the data from ASYNC task
    private void requestData(String uri) {
        MyTask task = new MyTask();
        task.execute(uri);
    }

    // method to check internet connectivity
    protected boolean isOnline(){
        ConnectivityManager cm =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        return netInfo != null && netInfo.isConnectedOrConnecting();

    }

    protected void updateDisplay(ArrayList<Places> placeList){

        // get instance of the Master List fragment then replaces container1 and commits it to the activity

        MasterFragment frag = MasterFragment.newInstance(placeList);

        getFragmentManager().beginTransaction()

                .replace(R.id.container1, frag, MasterFragment.TAG).commit();

    }






    // Async task method to do network action in
    private class MyTask extends AsyncTask<String ,String ,String>{

        @Override
        protected void onPreExecute() {
            // add this to the task
            tasks.add(this);
        }

        @Override
        protected String doInBackground(String... params) {
            return HttpManager.getData(params[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            tasks.remove(this);
            if(null != result && !result.isEmpty()) {
                placeList = JSONParser.parseFeed(result);
                updateDisplay(placeList);
            }else {
                Toast.makeText(MainActivity.this, "Can't connect to API", Toast.LENGTH_SHORT).show();

            }


        }

        @Override
        protected void onProgressUpdate(String... values) {

        }
    }

}

DetailFragment.java

package com.brianstacks.project1.fragments;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.brianstacks.project1.R;

/**
 * Created by Brian Stacks
 * on 10/27/14
 * for FullSail.edu.
 */
public class DetailFragment extends Fragment {

    public static final String TAG = "DetailFragment.TAG";
    public static final String ARG_TAG = "DetailFragment.TAG";

    public static DetailFragment newInstance(String myString) {
        DetailFragment frag = new DetailFragment();

        Bundle args = new Bundle();
        args.putString(ARG_TAG, myString);
        frag.setArguments(args);

        return frag;
    }

    @Override
    public View onCreateView(LayoutInflater _inflater, ViewGroup _container,
                             Bundle _savedInstanceState) {
        // Create and return view for this fragment.
        return _inflater.inflate(R.layout.detail_layout, _container, false);
    }

    @Override
    public void onActivityCreated(Bundle _savedInstanceState) {
        super.onActivityCreated(_savedInstanceState);

        Bundle args = getArguments();
        if(args != null && args.containsKey(ARG_TAG)){
            setDisplayInfo(args.getString(ARG_TAG));
        }

    }

    public void setDisplayInfo(String myText){
        getArguments().putString(ARG_TAG,myText);
        // Get our TextView and set some text to it.
        TextView tv;
        tv = (TextView)getView().findViewById(R.id.detailText);
        tv.setText(myText);
    }
}

MasterFragment.java

package com.brianstacks.project1.fragments;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListFragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.brianstacks.project1.JSONParser;
import com.brianstacks.project1.MainActivity;
import com.brianstacks.project1.Places;
import com.brianstacks.project1.PlacesAdapter;
import com.brianstacks.project1.R;

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

/**
 * Created by Brian Stacks
 * on 10/27/14
 * for FullSail.edu.
 */
public class MasterFragment extends ListFragment{

    public static final String TAG = "MasterFragment.TAG";
    public static final String KEY = "places";
    private OnListItemClickListener mListener;
    private ArrayList<Places> placeList2;


    public static MasterFragment newInstance(ArrayList<Places> placeList) {
        MasterFragment masterFragment = new MasterFragment();

        Bundle args = new Bundle();

        args.putSerializable("places", placeList);

        masterFragment.setArguments(args);

        return masterFragment;

    }

    public interface OnListItemClickListener{
        public void displayText(String myText);
    }


    @Override
    public void  onAttach(Activity activity){
        super.onAttach(activity);

        if (activity instanceof OnListItemClickListener){
            mListener = (OnListItemClickListener) activity;
        }else {
            throw new IllegalArgumentException("Containing Activity must implement the OnListItemClicked");
        }
    }

    @Override
    public void onActivityCreated(Bundle _savedInstanceState) {
        super.onActivityCreated(_savedInstanceState);
        if (_savedInstanceState == null){
            Bundle args = getArguments();
            String myStrings=args.getString("places");
            Log.v("Places",myStrings);

        /*String[] presidents = getResources().getStringArray(R.array.presidents);
        //ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, presidents);
        //PlacesAdapter adapter2 = new PlacesAdapter(this.getActivity(),R.layout.item_place,placeList);
        //setListAdapter(adapter2);

    }

    @Override
    public void onListItemClick(ListView _l, View _v, int _position, long _id) {
        String president = (String)_l.getItemAtPosition(_position);
        mListener.displayText(president);
        */
        }

    }
}

HTTPManager.java

package com.brianstacks.project1;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Brian Stacks
 * on 10/20/14
 * for FullSail.edu.
 */
public class HttpManager {

    public  static  String getData(String uri){
        BufferedReader reader = null;

        try {
            URL url = new URL(uri);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            StringBuilder sb = new StringBuilder();
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null){
                sb.append(line).append("");
            }
            return sb.toString();

        }catch (Exception e){
        e.printStackTrace();
            return null;
        }finally {
            if (reader!=null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

JSONParser.java

package com.brianstacks.project1;


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

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Brian Stacks
 * on 10/20/14
 * for FullSail.edu.
 */
public class JSONParser {

    public static ArrayList<Places> parseFeed(String content) {


        JSONObject myObj;
        try {
            myObj = new JSONObject(content);
            JSONArray result = myObj.getJSONArray("results");
            ArrayList<Places> placeList = new ArrayList<>();

            for (int i = 0; i < result.length(); i++) {
                JSONObject obj = result.getJSONObject(i);
                Places place = new Places();
                place.setName(obj.getString("name"));
                place.setFormatted_address(obj.getString("formatted_address"));
                place.setTypes(obj.getString("types"));
                //place.setPhotos(obj.getString("photos"));

                placeList.add(place);
            }
            return placeList;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }

    }

}

Places.java

import java.io.Serializable;

/**
 * Created by Brian Stacks
 * on 10/22/14
 * for FullSail.edu.
 */
public class Places implements Serializable {

    private String pName;
    private String pTypes;
    private String pFormatted_address;


    public Places(){
        pName ="";
        pTypes ="";
        pFormatted_address = "";
    }

    public String getName() {
        return pName;
    }
    public void setName(String name) {
        pName = name;
    }
    public String getTypes() {
        return pTypes;
    }
    public void  setTypes(String types) {
        pTypes= types;
    }
    public String getFormatted_address() {
        return pFormatted_address;
    }
    public void setFormatted_address(String formatted_address) {
        pFormatted_address=formatted_address;
    }


}

非常感谢任何帮助

也在阅读这篇文章,但无济于事LINK

1 个答案:

答案 0 :(得分:2)

我找到了解决这个问题的方法,当代码期望Object改变了这一点时,我试图将我的String强制转换为我的MasterFragment.java ArrayList<Places>它的代码和权力,没有错误。

旧代码

Bundle args = getArguments();
String myStrings=args.getString("places");

新代码

Bundle args = getArguments();
ArrayList myStrings = args.getParcelableArrayList("places");