创建显示空指针异常的新Intent

时间:2014-12-05 16:08:51

标签: java android android-intent dialog

创建显示nullpointer异常的新intent,作为初学者,我需要帮助来解决它。感谢

MainActivity.java

公共类MainActivity扩展了Activity {

ProgressBar progressBar=null;
ArrayList<String> Results=null;
EditText getStory = null;
String strStory=null;
String story=null;
ImageView imgFavorite;
int click;
/*EditText editText =null;*/
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    progressBar = (ProgressBar) findViewById(R.id.resultProgressBar);
    Results = new ArrayList<String>();

    ImageView imageView = (ImageView) findViewById(R.id.imageArchieveView);
    //imageView.setImageResource        (R.drawable.image1);

    imageView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            openDialog();
        }
    });

}

private void openDialog() {
    DialogArchive dialogArchive = new DialogArchive();
    dialogArchive.show(getFragmentManager(),"Myfragment");
}

public void getClicked(int number) {
    this.click = number;
    getStory();
}

public void getStory() {
    StoryDictionary storyDictionary = new StoryDictionary();

    //Log.d("aaa333", storyDictionary.getStory(click));

    try {
        SearchResult(textFormation(storyDictionary.getStory(click)));
    } catch (Exception e) {
        e.printStackTrace();
    }
}


public void SearchResult(String getStory) throws IOException, ExecutionException, InterruptedException {
    //Log.d("aaa333", getStory);
    Token token = new Token("fox enter partnership lion pretens becom servant undertook proper duti accord natur power fox discov point prei lion sprang and seiz fox soon becam jealou lion carri lions share said longer find prei captur account next dai attempt snatch lamb fold fell prei huntsmen hound");
    HashMap<String, Integer> map = token.doTokenization();
    Testing test = new Testing(map);
    TreeMap<String, Integer> sorted_map = test.getSortedMap();

    ArrayList<String> c = new ArrayList<String>(sorted_map.keySet());
    String finalQuery= "";
    for(int i=0;i<3;i++)
    {
        finalQuery += c.get(i).toString()+" ";
    }

    System.out.println(finalQuery);

    ResourceInternettask resourceInternettask = new ResourceInternettask();
    resourceInternettask.execute(finalQuery);
    //Results.clear();
    try {
        Results = resourceInternettask.get();
        for(int i=0;i<Results.size();i++)
        Log.d("aaa333", Results.get(i).toString());

    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    callIntent();
}

public void callIntent()
{
    Intent intent;
    intent = new Intent(MainActivity.this, ResultsActivity.class);
    intent.putStringArrayListExtra("searchResults",Results);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    // Add new Flag to start new Activity
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    startActivity(intent);
}
public String textFormation(String string) throws IOException {
    RemoveStopWords stopWords = new RemoveStopWords(PStemmer.main(string));
    return stopWords.getRemovedStopWords();
}

 public class ResourceInternettask extends AsyncTask<String, Integer, ArrayList<String>> {
    String Key = "key";
    URL url = null;
    HttpURLConnection conn = null;
    private int contentLength=-1;
    int counter =0;
    int calculatedProgress =0;
    @Override
    protected void onPreExecute() {
        //progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    protected ArrayList<String> doInBackground(String... Param) {
        String Query = Param[0].replace(" ", "+");               /*"the%20lion%20and%20the%20mouse";*/
        ArrayList<String> Results = new ArrayList<String>();
        ArrayList<String> updatedResults = new ArrayList<String>();
        ArrayList<String> Photos  = new ArrayList<String>();
        try {
            url = new URL("https://www.googleapis.com/customsearch/v1?key=" + Key + "&cx=013036536707430787589:_pqjad5hr1a&q=" + Query + "&alt=json");
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");
            contentLength = conn.getContentLength();
            BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
            String output;
            int i = 0;

            while ((output = br.readLine()) != null) {
                if (output.contains("\"link\": \"")) {

                    String link = output.substring(output.indexOf("\"link\": \"") + ("\"link\": \"").length(), output.indexOf("\","));

                    Results.add(link);
                }
                if (output.contains("\"title\": \"")) {
                    String title = output.split("\"")[3];
                    if (i > 2) {
                        Results.add(title);
                    }
                    i++;
                }

                if(output.contains("\"src\": \"")){
                    if(output.contains("https:")){
                        String photo = output.split("\"")[3];
                        Results.add(photo);
                    }

                }

                counter += output.length();
                publishProgress(counter);

            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            conn.disconnect();
        }
        return Results;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        calculatedProgress = (int)(((double)values[0]/contentLength)*100);
        //Log.d("Banik","ami "+calculatedProgress);
       // progressBar.setProgress(calculatedProgress);
    }

    @Override
    protected void onPostExecute(ArrayList<String> strings) {
        //Log.d("Andro2", "" + strings.size());
       // progressBar.setVisibility(View.GONE);
    }
}

}

DialogArchive.java

public Dialog onCreateDialog(Bundle savedInstanceState){

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Choose Story");
    builder.setItems(R.array.Stories, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
           // Toast.makeText(getActivity(), "item selected" + i, Toast.LENGTH_SHORT).show();
                dismiss();
                MainActivity mainActivity = new MainActivity();
                mainActivity.getClicked(i);
        }
    });
    Dialog dialog =builder.create();
    return dialog;
}

例外

12-05 10:46:00.666    1721-1721/? W/System.err﹕ java.lang.NullPointerException
12-05 10:46:00.716    1721-1721/? W/System.err﹕ at android.content.ContextWrapper.getPackageName(ContextWrapper.java:135)
12-05 10:46:00.716    1721-1721/? W/System.err﹕ at android.content.ComponentName.<init>(ComponentName.java:77)
12-05 10:46:00.716    1721-1721/? W/System.err﹕ at android.content.Intent.<init>(Intent.java:3813)
12-05 10:46:00.726    1721-1721/? W/System.err﹕ at children.apps.banik.children.MainActivity.callIntent(MainActivity.java:121)
12-05 10:46:00.726    1721-1721/? W/System.err﹕ at children.apps.banik.children.MainActivity.SearchResult(MainActivity.java:115)
12-05 10:46:00.726    1721-1721/? W/System.err﹕ at children.apps.banik.children.MainActivity.getStory(MainActivity.java:71)
12-05 10:46:00.726    1721-1721/? W/System.err﹕ at children.apps.banik.children.MainActivity.getClicked(MainActivity.java:62)
12-05 10:46:00.726    1721-1721/? W/System.err﹕ at children.apps.banik.children.DialogArchive$1.onClick(DialogArchive.java:26)
12-05 10:46:00.726    1721-1721/? W/System.err﹕ at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:941)
12-05 10:46:00.726    1721-1721/? W/System.err﹕ at android.widget.AdapterView.performItemClick(AdapterView.java:299)
12-05 10:46:00.726    1721-1721/? W/System.err﹕ at android.widget.AbsListView.performItemClick(AbsListView.java:1113)
12-05 10:46:00.726    1721-1721/? W/System.err﹕ at android.widget.AbsListView$PerformClick.run(AbsListView.java:2904)
12-05 10:46:00.756    1721-1721/? W/System.err﹕ at android.widget.AbsListView$3.run(AbsListView.java:3638)
12-05 10:46:00.756    1721-1721/? W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:733)
12-05 10:46:00.756    1721-1721/? W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:95)
12-05 10:46:00.756    1721-1721/? W/System.err﹕ at android.os.Looper.loop(Looper.java:136)
12-05 10:46:00.756    1721-1721/? W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5017)
12-05 10:46:00.766    1721-1721/? W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
12-05 10:46:00.766    1721-1721/? W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:515)
12-05 10:46:00.766    1721-1721/? W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
12-05 10:46:00.766    1721-1721/? W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
12-05 10:46:00.766    1721-1721/? W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
12-05 10:46:00.766    1721-1721/? I/Choreographer﹕ Skipped 402 frames!  The application may be doing too much work on its main thread.
12-05 10:46:00.866      396-554/? W/InputMethodManagerService﹕ Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy@b3f76218 attribute=null, token = android.os.BinderProxy@b401e058
12-05 10:46:54.496      396-457/? D/LightsService﹕ Excessive delay setting light: 59ms

1 个答案:

答案 0 :(得分:1)

问题是DialogArchive.java中的这一行:

MainActivity mainActivity = new MainActivity();

您永远不应该自己实例化活动等应用程序组件。以这种方式实例化Activity时,Android没有机会将Context信息附加到它们。您需要从DialogFragment获取对Android创建的MainActivity (实际在屏幕上的那个)的引用。这通常在onAttach()方法内完成。如果只能从MainActivity中显示此片段,则可以执行以下操作:

private MainActivity mainActivity;

@Override
public void onAttach (Activity activity) {
    super.onAttach(activity);
    if (!(activity instanceof MainActivity)) {
        throw new IllegalStateException("Must be attached to an instance of MainActivity!");
    }
    mainActivity = (MainActivity) activity;
}

然后,当您构建对话框时,只需拨打mainActivity.getClicked(i)

即可
builder.setItems(R.array.Stories, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
        dismiss();
        mainActivity.getClicked(i);
    }
});