0

I have 2 problems: 1) When I tried to load the fragment2 into mainactivity directly during oncreate () it does not display anything 2) when I created a button to go to fragment2 and clicked the button To go to fragment2, it goes to fragment2 but goes after the second click or double click on the same button. i have tried using setfocusableintouchmode= true and false both, but getting same results, button works after same 2 clicks.so whats with this network operations? how can i display results of fragment2 network operations to be shown in mainactivity ? and what about button? heres my code:

my Androidmanifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   >
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Heres my mainactivity:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

public class MainActivity extends AppCompatActivity {

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


        Fragment frag2 = new Fragment2();
        FragmentTransaction transaction =getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fl, frag2);
        transaction.addToBackStack(null);
        transaction.commit();
        Log.i("reaktion","commited");



        b1=(Button)findViewById(R.id.f1);
        b2=(Button)findViewById(R.id.f2);
        b2.setFocusableInTouchMode(false);

//
//        Fragment2 frag2= new Fragment2();
//        FragmentManager manager = getSupportFragmentManager();
//        FragmentTransaction transaction = manager.beginTransaction();  //// I tried this, but as I said, it does nothing on oncreate ()
//        transaction.replace(R.id.fl,frag2);
//        transaction.commit();
//

    }
    public void frag1(View view){


        Fragment newFragment = new Fragment1();

        FragmentTransaction transaction =getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fl, newFragment);
        transaction.addToBackStack(null);
        transaction.commit();



    }
    public void frag2(View view){


        Fragment2 frag2= new Fragment2();
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.fl,frag2);
        transaction.commit();


    }


}

my fragment1:

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;


public class Fragment1 extends Fragment {

Button btn;
    public Fragment1() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        container.removeAllViewsInLayout();
        View v= inflater.inflate(R.layout.fragment_fragment1, container, false);
        btn=(Button)v.findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                Fragment2 frag2= new Fragment2();
                FragmentManager manager = getFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();
                transaction.replace(R.id.fl,frag2);
                transaction.commit();







            }
        });
        // Inflate the layout for this fragment
        return v;
    }

}

my fragment2:

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

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

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

import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;




public class Fragment2 extends Fragment {

    static String   j="";
    RecyclerView rv;
    private GridLayoutManager gridLayoutManager;
    private myadapter adapter;

    ArrayList<String> company_namelist;
    ArrayList<String> company_websitelist;

String JR;
    public Fragment2() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        container.removeAllViewsInLayout();

        // Inflate the layout for this fragment
        View view= inflater.inflate(R.layout.fragment_fragment2, container, false);

        company_namelist =new ArrayList<>();
        company_websitelist=new ArrayList<>();


        loaddata();
Log.i("loadhua","connection request made");
        rv = (RecyclerView)view.findViewById(R.id.recycler_view);

        LinearLayoutManager linearLayoutManager= new LinearLayoutManager(getActivity());
        adapter = new myadapter(company_namelist,company_websitelist);

        rv.setLayoutManager(linearLayoutManager);
        rv.setFocusableInTouchMode(false);
        Log.i("jojojo","recycler has setted the adapter");
        rv.setAdapter(adapter);


        return view;
    }

public void loaddata(){


   companyfromserver obj = new companyfromserver();
    JSONObject a = new JSONObject();

    try {
        a.put("nothing","nothing" );



    } catch (JSONException e) {
        e.printStackTrace();
    }
    obj.execute(String.valueOf(a));
    JR=obj.getJR();
Log.i("nacho",JR);


try{
    JSONObject jsonObject = new JSONObject(JR);
    JSONArray jsonArray = jsonObject.getJSONArray("data");

    for(int i=0;i<jsonArray.length();i++){

        JSONObject jsondata = jsonArray.getJSONObject(i);
        String company_name= jsondata.getString("company_name");
        String company_website=jsondata.getString("company_website");


        company_namelist.add(company_name);
        company_websitelist.add(company_website);

    }



}catch (JSONException e){}

        }




}

companyfromserver:

import android.os.AsyncTask;
import android.util.Log;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;

class companyfromserver extends AsyncTask<String, String, String> {


    public static String   j="";
    @Override
    protected String doInBackground(String... params) {

        String JsonResponse = "";
        String JsonDATA = params[0];
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;
        try {
            URL url = new URL("example.com");
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setDoOutput(true);
            // is output buffer writter
            urlConnection.setRequestMethod("POST");
            urlConnection.setRequestProperty("Content-Type", "application/json");
            urlConnection.setRequestProperty("Accept", "application/json");
//set headers and method
            Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
            writer.write(JsonDATA);
// json data
            writer.close();
            InputStream inputStream = urlConnection.getInputStream();
//input stream
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                // Nothing to do.
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String inputLine;
            while ((inputLine = reader.readLine()) != null)
                buffer.append(inputLine + "\n");
            if (buffer.length() == 0) {
                // Stream was empty. No point in parsing.
                return null;
            }
            JsonResponse = buffer.toString();

            j=j+JsonResponse;

            Log.i("xyz",j);
//response data
            Log.i("o/p:", JsonResponse);



//send to post execute


        }

        catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e("wtf", "Error closing stream", e);
                }
            }
        }
        return  j;
    }






    public String getJR(){
        Log.i("klopp",j);
        return j; }


}

mainactivity.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
  >
    <RelativeLayout
        android:id="@+id/rl"
        android:layout_width="0dp"
        android:layout_height="0dp"
        tools:layout_constraintTop_creator="1"
        tools:layout_constraintRight_creator="1"
        tools:layout_constraintBottom_creator="1"
        android:layout_marginStart="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_marginEnd="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginTop="8dp"
        tools:layout_constraintLeft_creator="1"
        android:layout_marginBottom="8dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp">
        <FrameLayout
            android:id="@+id/fl"
            android:layout_marginTop="60sp"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </FrameLayout>
        <Button
            android:id="@+id/f1"

            android:layout_width="100sp"
            android:layout_height="50sp"
            android:text="f1"
            android:onClick="frag1"/>

        <Button
            android:layout_toRightOf="@+id/f1"
            android:id="@+id/f2"
            android:layout_marginLeft="30sp"
            android:layout_width="100sp"
            android:layout_height="50sp"
            android:text="f2"
           />


    </RelativeLayout>



</android.support.constraint.ConstraintLayout>

Fragment1.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_gravity="center"
        android:gravity="center"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="fragment 1" />
    <Button
        android:id="@+id/btn"
        android:text="go"
        android:layout_margin="80sp"
        android:layout_width="140sp"
        android:layout_height="60sp" />

</FrameLayout>

fragment2.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >


    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:focusable="true"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clipToPadding="false"
        android:scrollbars="vertical" />
</FrameLayout>
kloss91
  • 33
  • 1
  • 8

1 Answers1

0

Either bind data in onPostExecute or use callbacks.

obj.execute(String.valueOf(a));

/* Here you wont be getting data */
JR=obj.getJR();
Log.i("nacho",JR);
Pawan Gupta
  • 315
  • 1
  • 3
  • 16
  • no , i am getting data sir,but not in that mainactivity, only through button press, and even if i implement onpostexcute , inorder to send data to the adapter class i will have to use getter method right, i have used similar mechanism in my login too, it works , but works on double click. I want to know how to improve this. Why things not happen on first press. – kloss91 Aug 15 '17 at 11:43
  • Here I can see the problem is loading data from server is taking some time before that only your code below obj.execute(String.valueOf(a)); will execute. So there will be no data. On button click might be its loading the previous data. As its static public static String j=""; – Pawan Gupta Aug 15 '17 at 11:55
  • sir i am getting all the new data from server as well, and the only reason i have created j as static is so that i can use it anywhere easily. So what according to you now i should do ? if the code works in button click atleast after second click, why it never show anything in the same fragment in maincitivity when app start. – kloss91 Aug 15 '17 at 12:01
  • yes sir, i cannot see anything in logcat info nacho when app executes, but when i click button it shows data coming from web in it, so what should i do now inorder to execute the asynctask class in the opening of app? – kloss91 Aug 15 '17 at 12:39
  • https://stackoverflow.com/questions/9963691/android-asynctask-sending-callbacks-to-ui check the answer (2) – Pawan Gupta Aug 16 '17 at 06:45