MrErfan MrErfan - 4 months ago 16
JSON Question

how show mylist in activity to fragment android

I wish I got the information from a site within a fragment showing my list
See the following code :

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.musiqikurdi.app.appmusiqikurdi.Models.MusicModel;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
TabLayout tablayout;
ViewPager viewpager;
ViewPagerAdapter viewPagerAdapter;
private ListView lv;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);







final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();

NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);

toolbar.setNavigationOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
if (drawer.isDrawerOpen(Gravity.RIGHT)) {
drawer.closeDrawer(Gravity.RIGHT);
} else {
drawer.openDrawer(Gravity.RIGHT);
}
}
});
//tablayout
tablayout = (TabLayout) findViewById(R.id.tabLayout);
viewpager = (ViewPager) findViewById(R.id.viewPager);
//ViewPagerAdapter
viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragments(new HomeFragment(),"Home");
viewPagerAdapter.addFragments(new PostFragment(),"New");

viewpager.setAdapter(viewPagerAdapter);
tablayout.setupWithViewPager(viewpager);



}

@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(Gravity.RIGHT)) {
drawer.closeDrawer(Gravity.RIGHT);
} else {
super.onBackPressed();
}
}

@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();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();

if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {

} else if (id == R.id.nav_slideshow) {

} else if (id == R.id.nav_manage) {

} else if (id == R.id.nav_share) {

} else if (id == R.id.nav_send) {

}

DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(Gravity.RIGHT);
return true;
}
public class mytask extends AsyncTask<String,String,List<MusicModel>> {

@Override
protected List<MusicModel> doInBackground(String... params) {

HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();

InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));

StringBuffer buffer = new StringBuffer();

String line = "";
while ((line = reader.readLine()) != null)
{
buffer.append(line);
}
String finalJSON = buffer.toString();
JSONObject parentobject = new JSONObject(finalJSON);
JSONArray parentarray = parentobject.getJSONArray("posts");
StringBuffer finalbufferData = new StringBuffer();


List<MusicModel> musicModelList = new ArrayList<>();

for(int i=0; i < parentarray.length(); i++) {
JSONObject finalobject = parentarray.getJSONObject(i);
MusicModel musicModel = new MusicModel();
musicModel.setId(finalobject.getString("id"));
musicModel.setTitle(finalobject.getString("title").replaceAll("[\\&#8211;]", ""));
musicModel.setUrl(finalobject.getString("url").replaceAll("[\\&#8211;]", ""));
musicModel.setDate(finalobject.getString("date").replaceAll("[\\&#8211;]", ""));

List<MusicModel.category> cateList = new ArrayList<>();
for(int j = 0; j < finalobject.getJSONArray("categories").length(); j++ )
{
MusicModel.category cate = new MusicModel.category();
cate.setCateTitle(finalobject.getJSONArray("categories").getJSONObject(j).getString("title"));
cateList.add(cate);
}
musicModel.setListCategory(cateList);
musicModelList.add(musicModel);
}

return musicModelList;

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}finally {
if(connection != null) {
connection.disconnect();
}
try {
if(reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;

}

@Override
protected void onPostExecute(List<MusicModel> s) {
super.onPostExecute(s);
musicAdapter adapter = new musicAdapter(getApplicationContext(),R.layout.row,s);
lv.setAdapter(adapter);
}
}

public class musicAdapter extends ArrayAdapter{
private List<MusicModel> musicModelList;
private int resource;
private LayoutInflater inflater;
public musicAdapter(Context context, int resource, List<MusicModel> objects) {
super(context, resource, objects);
musicModelList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}

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

if(convertView == null)
{
convertView = inflater.inflate(R.layout.row,null);
}
ImageView img;
TextView txt1;
TextView txt2;
TextView txt3;

img = (ImageView)convertView.findViewById(R.id.img);
txt1 = (TextView)convertView.findViewById(R.id.txt1);
txt2 = (TextView)convertView.findViewById(R.id.txt2);
txt3 = (TextView)convertView.findViewById(R.id.txt3);

txt1.setText(musicModelList.get(position).getId());
txt2.setText(musicModelList.get(position).getTitle());
return convertView;
}
}

}


As you can see in the activity of the work I've done is I want it in my mouth homefragment displayed, please guide me

Answer

You have two tabs in your activity( Home and New) right? And you want to display the content in Home fragment? If that is what you meant,

  1. Execute the AsyncTask in HomeFragment class. And execute the AsyncTask in OnCreateView() method or OnViewCreated() method. I dont see execute statement in the code you pasted.

2.There is no need to change anything in AsyncTask part but if you have used "this" for context , use getActivity() in its place.

3.Keep Navigation drawer part's code and Toolbar items code in the activity itself.(Eg.onOptionsItemSelected(),onCreateOptionsMenu() etc)

4.Don't forget to move Adapter class to HomeFragment.

I think this helps.

I have edited your code, see if this works. public class HomeFragment extends Fragment {

public HomeFragment() {
    // Required empty public constructor
}

private ListView lv;

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    lv = (ListView) getActivity().findViewById(R.id.lv);
    new mytask().execute("http://musiqikurdi.com/api/get_recent_posts/");
}

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_home,container,false);

    return rootView;
}

public class mytask extends AsyncTask<String,String,List<MusicModel>> {

    @Override
    protected List<MusicModel> doInBackground(String... params) {

        HttpURLConnection connection = null;
        BufferedReader reader = null;
        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();

            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();

            String line = "";
            while ((line = reader.readLine()) != null)
            {
                buffer.append(line);
            }
            String finalJSON = buffer.toString();
            JSONObject parentobject = new JSONObject(finalJSON);
            JSONArray parentarray = parentobject.getJSONArray("posts");
            StringBuffer finalbufferData = new StringBuffer();


            List<MusicModel> musicModelList = new ArrayList<>();

            for(int i=0; i < parentarray.length(); i++) {
                JSONObject finalobject = parentarray.getJSONObject(i);
                MusicModel musicModel = new MusicModel();
                musicModel.setId(finalobject.getString("id"));
                musicModel.setTitle(finalobject.getString("title").replaceAll("[\\&#8211;]", ""));
                musicModel.setUrl(finalobject.getString("url").replaceAll("[\\&#8211;]", ""));
                musicModel.setDate(finalobject.getString("date").replaceAll("[\\&#8211;]", ""));

                List<MusicModel.category> cateList = new ArrayList<>();
                for(int j = 0; j < finalobject.getJSONArray("categories").length(); j++ )
                {
                    MusicModel.category cate = new MusicModel.category();
                    cate.setCateTitle(finalobject.getJSONArray("categories").getJSONObject(j).getString("title"));
                    cateList.add(cate);
                }
                musicModel.setListCategory(cateList);
                musicModelList.add(musicModel);
            }

            return musicModelList;

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }finally {
            if(connection != null) {
                connection.disconnect();
            }
            try {
                if(reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;

    }

    @Override
    protected void onPostExecute(List<MusicModel> s) {
        super.onPostExecute(s);
        MusicAdapter adapter = new MusicAdapter(getActivity(),R.layout.row,s);
        lv.setAdapter(adapter);
    }
}
public class MusicAdapter extends ArrayAdapter {
    private List<MusicModel> musicModelList;
    private int resource;
    private LayoutInflater inflater;
    public MusicAdapter(Context context, int resource, List<MusicModel> objects) {
        super(getActivity(), resource, objects);
        musicModelList = objects;
        this.resource = resource;
        inflater = (LayoutInflater) getActivity().getSystemService(getActivity().LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if(convertView == null)
        {
            convertView = inflater.inflate(R.layout.row,null);
        }
        ImageView img;
        TextView txt1;
        TextView txt2;
        TextView txt3;

        img = (ImageView)convertView.findViewById(R.id.img);
        txt1 = (TextView)convertView.findViewById(R.id.txt1);
        txt2 = (TextView)convertView.findViewById(R.id.txt2);
        txt3 = (TextView)convertView.findViewById(R.id.txt3);

        txt1.setText(musicModelList.get(position).getId());
        txt2.setText(musicModelList.get(position).getTitle());
        return convertView;
    }
}

}

Comments