how to parsing with json from 2 different server? - android

i need help here.
i wanna do parse with json from 2 url server and then show the array at 1 listview.
this's my code.
public class MainActivity extends Activity {
private JSONObject jObject;
private String jsonResult ="";
private JSONObject jObject2;
private String jsonResult2 ="";
private String url = "http://10.0.2.2/kota/daftarkota.php";
private String url2 = "http://10.0.2.2/kota/delkota.php";
private String url3 = "http://www.hatsa.byethost33.com/kota_daftarkota.php";
String[] daftarid;
String[] daftarnama;
String[] daftarlatitude;
String[] daftarlongitude;
Menu menu;
public static MainActivity ma;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ma=this;
RefreshList();
}
public void RefreshList() {
try {
jsonResult = getRequest(url);
jObject = new JSONObject(jsonResult);
JSONArray menuitemArray = jObject.getJSONArray("kota");
daftarid = new String[menuitemArray.length()];
daftarnama = new String[menuitemArray.length()];
daftarlatitude = new String[menuitemArray.length()];
daftarlongitude = new String[menuitemArray.length()];
for (int i = 0; i < menuitemArray.length(); i++)
{
daftarid[i] = menuitemArray.getJSONObject(i).getString("id").toString();
daftarnama[i] = menuitemArray.getJSONObject(i).getString("nama").toString();
daftarlatitude[i] = menuitemArray.getJSONObject(i).getString("latitude").toString();
daftarlongitude[i] = menuitemArray.getJSONObject(i).getString("longitude").toString();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
jsonResult2 = getRequest(url3);
jObject2 = new JSONObject(jsonResult2);
JSONArray menuitemArray = jObject2.getJSONArray("kota");
daftarid = new String[menuitemArray.length()];
daftarnama = new String[menuitemArray.length()];
daftarlatitude = new String[menuitemArray.length()];
daftarlongitude = new String[menuitemArray.length()];
for (int i = 0; i < menuitemArray.length(); i++)
{
daftarid[i] = menuitemArray.getJSONObject(i).getString("id").toString();
daftarnama[i] = menuitemArray.getJSONObject(i).getString("nama").toString();
daftarlatitude[i] = menuitemArray.getJSONObject(i).getString("latitude").toString();
daftarlongitude[i] = menuitemArray.getJSONObject(i).getString("longitude").toString();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ListView ListView01 = (ListView)findViewById(R.id.ListView01);
ListView01.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, daftarnama));
ListView01.setSelected(true);
ListView01.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
final String selectionid = daftarid[arg2];
final String selectionnama = daftarnama[arg2];
final String selectionlatitude = daftarlatitude[arg2];
final String selectionlongitude = daftarlongitude[arg2];
final CharSequence[] dialogitem = {"Edit", "Delete"};
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Pilih ?");
builder.setItems(dialogitem, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch(item){
case 0 :
Intent i = new Intent(getApplicationContext(), EditActivity.class);
i.putExtra("id", selectionid);
i.putExtra("nama", selectionnama);
i.putExtra("latitude", selectionlatitude);
i.putExtra("longitude", selectionlongitude);
startActivity(i);
break;
case 1 :
getRequest(url2 + "?id=" + selectionid);
RefreshList();
break;
}
}
});
builder.create().show();
}});
((ArrayAdapter)ListView01.getAdapter()).notifyDataSetInvalidated();
}
/**
* Method untuk Mengirimkan data ke server
*/
public String getRequest(String Url){
String sret="";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(Url);
try{
HttpResponse response = client.execute(request);
sret =request(response);
}catch(Exception ex){
Toast.makeText(this,"Gagal "+sret, Toast.LENGTH_SHORT).show();
}
return sret;
}
/**
* Method untuk Menerima data dari server
*/
public static String request(HttpResponse response){
String result = "";
try{
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
}catch(Exception ex){
result = "Error";
}
return result;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
this.menu = menu;
menu.add(0, 1, 0, "Tambah").setIcon(android.R.drawable.btn_plus);
menu.add(0, 2, 0, "Refresh").setIcon(android.R.drawable.ic_menu_rotate);
menu.add(0, 3, 0, "Exit").setIcon(android.R.drawable.ic_menu_close_clear_cancel);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 1:
Intent i = new Intent(MainActivity.this, AddActivity.class);
startActivity(i);
return true;
case 2:
RefreshList();
return true;
case 3:
finish();
return true;
}
return false;
}
}
if i run it, the listview only show me the array from 'url' and there's nothing from 'url3'.
i don't know how should my code is, if i wanna make the listview show the array from 'url' and 'url3'.
thanks. :)

It actually looks the other way around. I guess you see the data from url3, since you create the array daftarnama twice - the second time with the data from url3. Use a List<String> instead of the array. Create the list just once and then add all the items from both urls. Also, you should rethink your code. You have a lot of duplicate code here (DRY - don't repeat yourself).

Related

android How to limit ListView items displayed?

Now I am using Local database to get and display item on application but I want to split the items and display them in different pages 1,2,3 and so on. How do I do that? This is the Code to display data and display all the items in ListView format. What do I do to limit the number of items on List? And please tell me where to make changes too, if you know.. Thanks
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer);
mToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.open,R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationView navigationView = (NavigationView)findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(this);
listView = (ListView)findViewById(R.id.listView);
adapter = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1);
listView.setAdapter(adapter);
new Connection().execute();
btn =(Button) findViewById(R.id.button2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openActivity2();
}
});
}
private void openActivity2() {
Intent in = new Intent(this,Main2Activity.class);
startActivity(in);
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
class Connection extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... strings) {
String result = "";
String host = "http://10.0.3.2/Client/docks.php";
try
{
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(host));
HttpResponse response = client.execute(request);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer stringBuffer = new StringBuffer("");
String line = "";
while ((line = reader.readLine())!=null)
{
stringBuffer.append(line);
break;
}
reader.close();
result = stringBuffer.toString();
}
catch(Exception e)
{
return new String("There exception: "+e.getMessage());
}
return result;
}
#Override
protected void onPostExecute(String result)
{
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
try {
JSONObject jsonResult = new JSONObject(result);
int success = jsonResult.getInt("success");
if(success==1)
{
JSONArray data = jsonResult.getJSONArray("abc");
for(int i = 0; i < data.length(); i++)
{
JSONObject data1 = data.getJSONObject(i);
int id = data1.getInt("dock_id");
String name = data1.getString("dock_name");
String description = data1.getString("dock_desc");
int flightarrival = data1.getInt("flight_arrival");
int count = data1.getInt("trolley_count");
String time = data1.getString("snapshot_time");
String line = id+"."+name+"-"+count+"-"+flightarrival+"-"+time;
adapter.add(line);
}
}
else
{
Toast.makeText(getApplicationContext(), "there is no data", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if(mToggle.onOptionsItemSelected(item))
{
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if( id == R.id.home)
{
Toast.makeText(this,"This is home", Toast.LENGTH_SHORT).show();
}
if( id == R.id.trolleycount)
{
Toast.makeText(this,"This is trolleycount", Toast.LENGTH_SHORT).show();
}
if( id == R.id.log)
{
Intent in = new Intent(this,MainActivity.class);
startActivity(in);
Toast.makeText(this,"You have successfully logged out of your account", Toast.LENGTH_SHORT).show();
}
return false;
}
Looks like you could modify this code in your onPostExecute() method:
JSONArray data = jsonResult.getJSONArray("abc");
for(int i = 0; i < data.length(); i++)
{
...
adapter.add(line);
}
What you could do is change your loop condition to check that i is less than both data.length() and also whatever limit you want to impose. Let's say your limit is 100:
JSONArray data = jsonResult.getJSONArray("abc");
for(int i = 0; i < Math.min(100, data.length()); i++)
{
...
adapter.add(line);
}
The Math.min() method will return whichever of the two numbers is smaller, so you'll get data.length() items when there are fewer than 100 items and you'll get 100 items when there are more.

Show new id for newly list when it is pressed

I wonder how to show the new list id when it is pressed? Currently the new list is showing the old list id instead itself, but when I close the app and reopen it again, it will display its id.
Firstly the data will retrieved from MySQL and load into android listView. (Assume it has only one list only).
ListView listViewUpdate;
String ID, iD;
public static final int PROJECT_REQUEST_CODE = 1;
public static final int CAMERA_REQUEST_CODE = 2;
int mClickedPosition;
String ReceiveProject, ReceiveDescription, ReceiveTimeIn, ReceiveTimeOut;
Integer ReceiveProgress;
String myJSON;
JSONArray details = null;
TextView totalHours;
String MiNtimeIn,MaXtimeOut;
List<DetailsBean> details1=new ArrayList<>();
CustomBaseAdapter objadapter;
public void BuildEditDetails(final String ID) { // Assume the ID is foreign key
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://192.168.107.115/Android/CRUD/detailsRetrieve.php?id=" + ID);
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void showList() {
try {
JSONObject jsonObj = new JSONObject(myJSON);
details = jsonObj.getJSONArray(Configs.TAG_RESULTS);
for (int i = 0; i < details.length(); i++) {
JSONObject c = details.getJSONObject(i);
String project = c.getString(Configs.TAG_PROJECT);
String description = c.getString(Configs.TAG_WORKDESCRIPTION);
int percentage = c.getInt(Configs.TAG_PERCENTAGE);
String in = c.getString(Configs.TAG_IN);
String out = c.getString(Configs.TAG_OUT);
iD = c.getString(Configs.TAG_ID); // its real id
DetailsBean dbean=new DetailsBean(iD,project,description,percentage,in,out);
details1.add(dbean);
}
objadapter=new CustomBaseAdapter(getActivity(),details1);
listViewUpdate.setAdapter(objadapter);
} catch (JSONException e) {
e.printStackTrace();
}
When pen icon is clicked (mClickedPosition==-1), it will intent to Activity B ,and add a new list in Activity A listView. If list is pressed**(mClickedPosition!==1), it shows its id, and intent to **B for user to edit.
listViewUpdate.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
mClickedPosition = position;
String iD = details1.get(position).getID();
Intent intent = new Intent(getActivity(), Edit_Details.class);
intent.putExtra("iD", iD);
intent.putExtra("ID", ID);
intent.putExtra("mClickedPosition", mClickedPosition);
Toast.makeText(getActivity(), "This is" + iD + ID, Toast.LENGTH_LONG).show();
startActivityForResult(intent, PROJECT_REQUEST_CODE);
}
});
#Override public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.addDetails:
mClickedPosition = -1;
Intent intent = new Intent(getActivity(), Edit_Details.class);
intent.putExtra("ID", ID);
// intent.putExtra("iD", iD);
startActivityForResult(intent, PROJECT_REQUEST_CODE);
break;
OnActivityResult Activity A
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) { // receive from Activity B and populate ListView A
if (resultCode == Activity.RESULT_OK) {
if (requestCode == PROJECT_REQUEST_CODE) {
ReceiveProject = data.getStringExtra("project1");
ReceiveDescription = data.getStringExtra("description");
ReceiveProgress = data.getIntExtra("progress", 0);
ReceiveTimeIn = data.getStringExtra("timeIn");
ReceiveTimeOut = data.getStringExtra("timeOut");
if(mClickedPosition==-1)
{ // add list
if(objadapter!=null)
{
objadapter.addNewItem(iD,ReceiveProject,ReceiveDescription,ReceiveProgress,ReceiveTimeIn,ReceiveTimeOut);
}
}
else
{ // update list
if(objadapter!=null)
{
objadapter.changeItem(mClickedPosition,iD,ReceiveProject,ReceiveDescription,ReceiveProgress,ReceiveTimeIn,ReceiveTimeOut);
}
}
}
}
Finally CustomBaseAdapter
public class CustomBaseAdapter extends ArrayAdapter<DetailsBean>{ // for ListView
Activity context;
List<DetailsBean> details;
public CustomBaseAdapter(Activity context,List<DetailsBean> details) {
super(context, R.layout.retrieve_details, details);
this.context = context;
this.details = details;
}
public void changeItem(int m,String ID,String Project,String Description,int Percentage,String in,String out)
{
DetailsBean obj = new DetailsBean(ID, Project, Description, Percentage, in, out);
obj.setProject(Project);
obj.setProgress(Percentage+"");
obj.setTimeIn(in);
obj.setTimeOut(out);
obj.setDescription( Description);
details.set(m,obj);
this. notifyDataSetChanged();
}
public void addNewItem(String ID,String Project,String Description,int Percentage,String in,String out) {
DetailsBean obj = new DetailsBean(ID, Project, Description, Percentage, in, out);
obj.setProject(Project);
obj.setProgress(Percentage+"");
obj.setTimeIn(in);
obj.setTimeOut(out);
obj.setDescription( Description);
details.add(obj);
this.notifyDataSetChanged();
}
New list already can added below the previous list, but when I click
the new list, it still showing the old list id..How can I make it
display its id? Thanks
When come to this class, it retrieve value from MySQL
When I click 1 list or 2 list, it display their id, (1 and 2)
Now I added a new list , 3 list now
when I click the third list, it suppose to display 3 but it display 2
Show new id for newly list when it is pressed
Use onPostExecute of AddMore class for getting latest id and sending data back to previous Activity.like:
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
try{
JSONObject jsonObject=new JSONObject(s);
int latestID=jsonObject.optInt("lastId");
//call setResult here
....
returnIntent.putExtra("project1", project1);
returnIntent.putExtra("description", description);
returnIntent.putExtra("progress", progress);
returnIntent.putExtra("timeIn", timeIn);
returnIntent.putExtra("iD", latestID); //<<<
}catch(Exception ex){
}
}
Try in adapter CustomBaseAdapter class:
public List<DetailsBean> getDetails(){
return details;
}
in onItemClick
#Override
public void onItemClick(AdapterView<?> listView, View view,
int position, long id) {
mClickedPosition = position;
String iD = listViewUpdate.getDetails().get(position).getID();
//so check id here
....
check onActivityResult:
what is iD ?? What is value of this variable?
objadapter.addNewItem(iD,ReceiveProject,ReceiveDescription,ReceiveProgress,ReceiveTimeIn,ReceiveTimeOut

Solve startActivity in fragment

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:
Screen when I use getActivity():
You should start new Activity using Activity context:
getActivity.startActivity(intent);
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);
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.

my llistview load multiple time same data on screen

my listview repeat data some time which click on buttons fastly what do i do please help me see this images http://imgur.com/ed5uDtp after some time is show like this http://imgur.com/jAt4yn7
is show correctly data on listview but some time when click fastly buttons is load duplicate data how i will fixed this? plaa help me
public class thirdstep extends Activity implements View.OnClickListener {
int count = 0;
String id;
String title;
String tmpString, finaldate;
String valll;
ProgressBar prgLoading;
TextView txtAlert;
int IOConnect = 0;
String mVal9;
Button e01;
Button e02;
Button e03;
Button e04;
Button e05;
String SelectMenuAPI;
String url;
String URL;
String URL2, URL3, URL4;
String menu_title;
JSONArray school;
ListView listCategory;
String status;
String School_ID;
String Menu_ID;
String School_name;
String Meal_groupid;
String _response;
String _response2;
String CategoryAPI;
String SelectMenuAPI2;
TextView menu_nametxt;
thirdstepAdapter cla;
static ArrayList<Long> Category_ID = new ArrayList<Long>();
static ArrayList<String> school_name = new ArrayList<String>();
static ArrayList<String> menu_name = new ArrayList<String>();
static ArrayList<String> dish_name = new ArrayList<String>();
static ArrayList<String> dish_ID = new ArrayList<String>();
static ArrayList<String> day = new ArrayList<String>();
static ArrayList<Long> Vacation_ID = new ArrayList<Long>();
static ArrayList<String> Vacation_name = new ArrayList<String>();
static ArrayList<String> Vacation_Date = new ArrayList<String>();
String mydate;
String mode;
String s2;
ArrayList<String> myList,myList2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list2);
listCategory = (ListView) findViewById(R.id.thirdscreenlist);
prgLoading = (ProgressBar) findViewById(R.id.prgLoading);
txtAlert = (TextView) findViewById(R.id.txtAlert);
e01 = (Button) findViewById(R.id.e01);
e02 = (Button) findViewById(R.id.e02);
e03 = (Button) findViewById(R.id.e03);
e04 = (Button) findViewById(R.id.e04);
e05 = (Button) findViewById(R.id.e05);
e01.setOnClickListener(this);
e02.setOnClickListener(this);
e03.setOnClickListener(this);
e04.setOnClickListener(this);
e05.setOnClickListener(this);
cla = new thirdstepAdapter(thirdstep.this);
listCategory.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent(thirdstep.this, fifthscreen.class);
startActivity(intent);
}
});
new getDataTask().execute();
}
void clearData() {
Category_ID.clear();
school_name.clear();
menu_name.clear();
dish_name.clear();
dish_ID.clear();
day.clear();
Vacation_ID.clear();
Vacation_name.clear();
Vacation_Date.clear();
}
public class getDataTask extends AsyncTask<Void, Void, Void> {
getDataTask() {
if (!prgLoading.isShown()) {
prgLoading.setVisibility(0);
txtAlert.setVisibility(8);
}
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
}
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
parseJSONData();
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
prgLoading.setVisibility(8);
if ((Category_ID.size() > 0) || IOConnect == 0) {
listCategory.setAdapter(cla);
cla.notifyDataSetChanged() ;
listCategory.invalidateViews();
} else {
txtAlert.setVisibility(0);
menu_nametxt.setText("");
listCategory.setVisibility(View.GONE);
}
}
}
public void parseJSONData() {
clearData();
SelectMenuAPI="";
SelectMenuAPI = Utils.Schoolmenu +Menu_ID+"&sid="+School_ID+"&lid=" +
SchoolLevelId+"&mealid="+Meal_groupid;
URL = SelectMenuAPI;
URL2 = URL.replace(" ", "%20");
try {
Log.i("url",""+URL2);
HttpClient client = new DefaultHttpClient();
HttpConnectionParams
.setConnectionTimeout(client.getParams(), 15000);
HttpConnectionParams.setSoTimeout(client.getParams(), 15000);
HttpUriRequest request = new HttpGet(URL2);
HttpResponse response = client.execute(request);
HttpEntity resEntity = response.getEntity();
_response=EntityUtils.toString(resEntity);
JSONObject json5 = new JSONObject(_response);
status = json5.getString("status");
if (status.equals("1")) {
JSONArray school5 = json5.getJSONArray("data");
}
}
else {
}
SelectMenuAPI2="";
SelectMenuAPI2 = Utils.SchoolVacation+mVal9;
// clearData();
URL3 = SelectMenuAPI2;
URL4 = URL3.replace(" ", "%20");
Log.i("url",""+URL4);
JSONObject json2 = new JSONObject(_response);
status = json2.getString("status");
if (status.equals("1")) {
if (Vacation_Date.contains(mydate)) {
message = "holiday";
JSONObject json4 = new JSONObject(str2);
status = json4.getString("status");
if (status.equals("1")) {
school = json4.getJSONArray("data");
for (int k = 0; k < school.length(); k++) {
JSONObject jb = (JSONObject) school .getJSONObject(k);
Vacation_ID.add((long) k);
String[] mVal = new String[school.length()];
if(school.getJSONObject(k).getString("date").equals(mydate))
{
mVal[k] = school.getJSONObject(k).getString("title");
mVal3 = mVal[k];
}
}
}
} else {
JSONArray school = json2.getJSONArray("data");
for (int i = 0; i < school.length(); i++) {
JSONObject object = school.getJSONObject(i);
if (object.getString("Schedule").equals("weekly")) {
if (object.getString("day").equals(Todayday)) {
Category_ID.add((long) i);
school_name
.add(object.getString("school_name"));
dish_ID.add(object.getString("dish_id"));
dish_name.add(object.getString("dish_name"));
menu_name.add(object.getString("menu_title"));
day.add(object.getString("day"));
count = count + 1;
String[] mVal = new String[school.length()];
for (int k = 0; k < school.length(); k++) {
mVal[k] = school.getJSONObject(k).getString("menu_title");
message = "weekly";
mVal2 = mVal[0];
}
}
if(dish_name != null &&
!dish_name.isEmpty())
{
message = "weekly";
}
else {
message = "error";
}
}
else {
message = "error";
}
}
}
}
else {
message = "error";
}
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
IOConnect = 1;
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.e01:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e02:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e03:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e04:
// do stuff;
listCategory.setVisibility(View.GONE);
new getDataTask().execute();
break;
case R.id.e05:
listCategory.setVisibility(View.GONE);
// do stuff;
new getDataTask().execute();
break;
}
}
}
You are calling asynctask twice and that is making all parts twice, I mean you are cleaning twice before filling and fill arrays twice. You should control your async task for do not execute before last one finished.
1-Create a boolean value
2-Put condition on onClicks:
if(yourBoolean){
new getDataTask().execute();}
3- in your asyncTask's onPreExecute make yourBoolean=false and onPostExecute make yourBoolean=true again.
Try this..
Just remove the below line and try it..
listCategory.invalidateViews();
because
ListView.invalidateViews() is used to tell the ListView to invalidate all its child item views (redraw them). Note that there not need to be an equal number of views than items. That's because a ListView recycles its item views and moves them around the screen in a smart way while you scroll.

Android Fragment - SlidingMenu - ListActivity

So I have the slidingmenu(jfeinstein10) library added to my project and the menu working. The problem I have run into is based on my app extends ListActivity.
I have seen a couple questions about this and most suggest extending to Fragment to get Fragments working for the menu. I wanted to know if there was a way to not use Fragments to get the menu list to work.
Every time I move to SlidingFragmentActivity or any other Fragment Activity, onListItemClick and other methods start breaking.
Below is my code:
public class MainListActivity extends ListActivity {
public static final int NUMBER_OF_POSTS = 20;
public static final String TAG = MainListActivity.class.getSimpleName();
protected JSONObject mBlogData;
protected ProgressBar mProgressBar;
private SlidingMenu menu;
static final String KEY_TITLE = "title";
static final String KEY_AUTHOR = "author";
static final String KEY_IMAGE = "image";
ListView list;
LazyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//setBehindContentView(R.layout.menu_frame);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
menu = new SlidingMenu(this);
menu.setMode(SlidingMenu.LEFT);
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
menu.setShadowWidth(5);
menu.setFadeDegree(0.35f);
menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
menu.setBehindWidth(R.dimen.shadow_width);
menu.setShadowDrawable(R.drawable.shadow);
menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
menu.setMenu(R.layout.menu_frame);
//getFragmentManager().beginTransaction().replace(R.id.menu_frame, new MenuFragment()).commit();
if(isNetworkAvailable()){
GetBlogPostsTask getBlogPostsTask = new GetBlogPostsTask();
mProgressBar.setVisibility(View.VISIBLE);
getBlogPostsTask.execute();
}else{
Toast.makeText(this, "Network is unavailable", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id){
super.onListItemClick(l, v, position, id);
try{
JSONArray jsonPosts = mBlogData.getJSONArray("items");
JSONObject jsonPost = jsonPosts.getJSONObject(position);
String blogSummary = jsonPost.getString("summary");
String blogUrl = jsonPost.getString("bitly");
Intent intent = new Intent(this, BlogWebViewActivity.class);
intent.setData(Uri.parse(blogSummary));
intent.putExtra("mUrl",blogUrl);
startActivity(intent);
}catch(JSONException e){
logException(e);
}
}
private void logException(Exception e) {
Log.e(TAG, "Exception caught!", e);
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if(networkInfo != null && networkInfo.isConnected()){
isAvailable = true;
}
return isAvailable;
}
public void handleBlogResponse() {
mProgressBar.setVisibility(View.INVISIBLE);
if(mBlogData == null){
updateDisplayForError();
}else{
try {
JSONArray jsonPosts = mBlogData.getJSONArray("items");
ArrayList<HashMap<String,String>> blogPosts = new ArrayList<HashMap<String,String>>();
for (int i=0;i<jsonPosts.length();i++){
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString(KEY_TITLE);
title = Html.fromHtml(title).toString();
String tag = post.getString(KEY_AUTHOR);
tag = Html.fromHtml(tag).toString();
String image = post.getString(KEY_IMAGE);
image = Html.fromHtml(image).toString();
HashMap<String, String> blogPost = new HashMap<String,String>();
blogPost.put(KEY_TITLE, title);
blogPost.put(KEY_AUTHOR, tag);;
blogPost.put(KEY_IMAGE, image);
blogPosts.add(blogPost);
}
list=getListView();
LazyAdapter adapter = new LazyAdapter(this, blogPosts);
list.setAdapter(adapter);
} catch (JSONException e) {
logException(e);
}
}
}
private void updateDisplayForError() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.error_title));
builder.setMessage(getString(R.string.error_message));
builder.setPositiveButton(android.R.string.ok,null);
AlertDialog dialog = builder.create();
dialog.show();
TextView emptyTextView = (TextView) getListView().getEmptyView();
emptyTextView.setText(getString(R.string.no_items));
}
private class GetBlogPostsTask extends AsyncTask<Object, Void, JSONObject>{
#Override
protected JSONObject doInBackground(Object... params) {
int responseCode = -1;
JSONObject jsonResponse = null;
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://www.domain.com/app_json.js");
try {
HttpResponse response = client.execute(httpget);
StatusLine statusLine = response.getStatusLine();
responseCode = statusLine.getStatusCode();
if(responseCode == HttpURLConnection.HTTP_OK){
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while((line = reader.readLine()) != null){
builder.append(line);
}
jsonResponse = new JSONObject(builder.toString());
}else{
Log.i(TAG, "HTTP Failed: "+responseCode);
}
} catch (MalformedURLException e) {
logException(e);
} catch (IOException e) {
logException(e);
}
catch(Exception e){
logException(e);
}
return jsonResponse;
}
#Override
protected void onPostExecute(JSONObject result){
mBlogData = result;
handleBlogResponse();
}
}
#Override
public void onBackPressed() {
if (menu.isMenuShowing()) {
menu.showContent();
} else {
super.onBackPressed();
}
}
}
I have the menu items stored in /values/array.xml as a string-array.
I have setup a fragment as well, but dont know how to access it without extending to Fragment from ListActivity.
Below is my Fragment based on the example fragments from github:
public class MenuFragment extends ListFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.menu_list, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] colors = getResources().getStringArray(R.array.menu_items);
ArrayAdapter<String> colorAdapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1, android.R.id.text1, colors);
setListAdapter(colorAdapter);
}
#Override
public void onListItemClick(ListView lv, View v, int position, long id) {
Fragment newContent = null;
switch (position) {
case 0:
//newContent = new ColorFragment(R.color.red);
break;
case 1:
//newContent = new ColorFragment(R.color.green);
break;
case 2:
//newContent = new ColorFragment(R.color.blue);
break;
case 3:
//newContent = new ColorFragment(android.R.color.white);
break;
case 4:
//newContent = new ColorFragment(android.R.color.black);
break;
}
if (newContent != null)
switchFragment(newContent);
}
// the meat of switching the above fragment
private void switchFragment(Fragment fragment) {
if (getActivity() == null)
return;
}
}
Thanks

Categories

Resources