-5

I have a problem in my code. My problem is related to the startActivity(). When the app is running on the emulator, it does not work. The line causing the problem is described in the end.

I tried to open a new activity (this, newactivity.class), however the problem persists.

UpdateAnsList

public class UpdateAnsList extends Fragment{

    /**
     * @param args
     */
    final static String ARG_POSITION_ANSWER = "position";
    private String jsonResult;
        private ListView listView;
    public int selsub;
    public Activity activity; 
    public String tagsub;
    private Context mContext;
    private Activity mact;



    public UpdateAnsList(Activity _activity){
         mact = _activity;
        this.activity = _activity;
        super.onAttach(_activity);
        mContext = this.activity.getApplicationContext();
    }

    public enum SubSectionAnswer {
        TagArt,
        TagBio

    }


    public void StartUpdateAnsList(int v, String o){
        tagsub = o;
        selsub = v;     
        SubSectionAnswer currentSub = SubSectionAnswer.valueOf(tagsub);
        listView = (ListView) this.activity.findViewById(R.id.listView11);

        selectItemAns(selsub,currentSub);
        accessWebService();
    }

    private void selectItemAns(int position, SubSectionAnswer currentSub) {

        switch(currentSub){

        case TagArt:

            switch(position){   
            case R.id.buttonArt001:
                url = "myip/newfolder/question_2.php";
                tagdb = "info_general";
                break;

            case R.id.buttonArt002:
                url = "http://myip/newfolder/question_1.php";
                tagdb = "info_animation";
                break; 

            case 2:

                break; 

            }

            break;

        case TagBio:

            switch(position){   
            case R.id.ButtonBio001:
                url = "http://myip/newfolder/question_4.php";
                tagdb = "info_general";
                break;

            case R.id.buttonBio002:
                url = "http://myip/newfolder/question_5.php";
                tagdb = "info_evolution";
                break; 

            case 2:

                break; 

            }

            break;

        }


    }




    // Async Task to access the web
    private class JsonReadTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... params) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(params[0]);
            try {
                HttpResponse response = httpclient.execute(httppost);
                jsonResult = inputStreamToString(
                        response.getEntity().getContent()).toString();
            }

            catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }



        private StringBuilder inputStreamToString(InputStream is) {
            String rLine = "";
            StringBuilder answer = new StringBuilder();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));

            try {
                while ((rLine = rd.readLine()) != null) {
                    answer.append(rLine);
                }
            }

            catch (IOException e) {
                // e.printStackTrace();
                //Toast.makeText(getApplicationContext(),
                //      "Error..." + e.toString(), Toast.LENGTH_LONG).show();
            }
            return answer;
        }

        @Override
        protected void onPostExecute(String result) {
            ListDrwaer();
        }
    }// end async task

    public void accessWebService() {
        JsonReadTask task = new JsonReadTask();
        // passes values for the urls string array
        task.execute(new String[] { url });
    }

    // build hash set for list view
    public void ListDrwaer() {
        List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();

        try {
            JSONObject jsonResponse = new JSONObject(jsonResult);
            JSONArray jsonMainNode = jsonResponse.optJSONArray(tagdb);

            for (int i = 0; i < jsonMainNode.length(); i++) {
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                String name = jsonChildNode.optString("employee name");
                String number = jsonChildNode.optString("content_text");
                //String outPut = name + "-" + number;
                String outPut = name;
                String outPut1 = number; 
                employeeList.add(createEmployee("Question", outPut,"textlong",number));
            }
        } catch (JSONException e) {
            Toast.makeText(this.activity, "Error" + e.toString(),
                    Toast.LENGTH_SHORT).show();
        }

        //new String[] { "employees" }
        //new int[] { android.R.id.text1 }
        String[] de = {"Question", "textlong"};
        int[] para ={R.id.textView1list11, R.id.textView11  };
        SimpleAdapter simpleAdapter = new SimpleAdapter(this.activity, employeeList,
                R.layout.activity_item_list_answer,
                de, para);
        listView.setAdapter(simpleAdapter);
        listView.setOnItemClickListener(new ListClickHandler());

        //Toast.makeText(getApplication(), "c", Toast.LENGTH_SHORT).show();

    }


    public class ListClickHandler implements OnItemClickListener{

        public void onItemClick(AdapterView<?> adapter, View view, int position, long arg3) {
            // TODO Auto-generated method stub
            int a =1 ;
            //Toast.makeText(mContext, "c", Toast.LENGTH_SHORT).show();
            //Intent i = new Intent(mact, QuestionActivity.class);
            //mContext.startActivity(i); 

            // create intent to perform web search for this planet
                        Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
                        intent.putExtra(SearchManager.QUERY, "test");
                        // catch event that there's no activity to handle intent
                        mContext.startActivity(intent);


        }

    }


    private HashMap<String, String> createEmployee(String s1, String s2, String s3,String s4) {
        HashMap<String, String> employeeNameNo = new HashMap<String, String>();
        employeeNameNo.put(s1, s2);
        employeeNameNo.put(s3, s4);
        return employeeNameNo;
    }




}

This is the line causing the problem:

mContext.startActivity(intent);

Screen of debug:

debug

Screen when I use getActivity():

screenshot

Adam Michalik
  • 9,678
  • 13
  • 71
  • 102
YVLM
  • 53
  • 1
  • 2
  • 5
  • Post your logcat please when the error happens – Jörn Buitink Dec 17 '15 at 12:17
  • You Cannot Start Activity Using Context. You either need a reference to current activity or in case of fragment you can do it simply by getActivity().startActivity(new Intent(....)); – Umer Kiani Dec 17 '15 at 12:18
  • Can you post your activity class also? – DimLek Dec 17 '15 at 12:39
  • Your ListClickHandler class must be declaired as static first. I'll post a better practice to solve your problem later. Note: Fragment has its own startActivity method, you can use that, but wisely – Nguyễn Hoài Nam Dec 17 '15 at 12:43

3 Answers3

1

You should start new Activity using Activity context:

getActivity.startActivity(intent);
Tanmay Sahoo
  • 471
  • 1
  • 6
  • 16
0

Basically you are working with Fragment:

How to Start Activity from Fragment:

mContext.startActivity(intent);

Edit 1:

private Context mContext;

 public void StartUpdateAnsList(Context ctx, int v, String o){
        mContext = ctx;
        tagsub = o;
        selsub = v;     
        SubSectionAnswer currentSub = SubSectionAnswer.valueOf(tagsub);
        listView = (ListView) this.activity.findViewById(R.id.listView11);

        selectItemAns(selsub,currentSub);
        accessWebService();
    }

Now you can use: mContext.startActivity(intent);

Hope this will help you.

Hiren Patel
  • 52,124
  • 21
  • 173
  • 151
  • How you can see. My getActivity is null. I do not know why – YVLM Dec 17 '15 at 12:36
  • Be careful to call getActivity() only when the fragment is attached to an activity. When the fragment is not yet attached, or was detached during the end of its lifecycle, getActivity() will return null. – DimLek Dec 17 '15 at 12:48
0

This is a Fragment class, so you are not able to pass an Intentby simply writing this.startActivity();
What you need to do is to get the Activity of this Fragment class.
So instead of mContext.startActivity(intent); you should write :

getActivity().startActivity(intent);
DimLek
  • 123
  • 8