我有一个活动,可以在URL json文件中进行搜索,因此3个参数从MainActivity的EditText传递到第二个活动(匿名),URL Json恢复了这三个值,结果通常显示出来,但是如果我返回MainActivity并更改EditTexts的值并单击“搜索”,则问题不会改变。
这是我的项目:
MainActivity.java
package com.example.dzweber.waslup;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
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.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
AutoCompleteTextView cat;
String[] categories={"informatique","infographie","mathématique","Génie civil","Biologie"};
@Override
protected void onCreate(Bundle savedInstanceState) {
if(annonces.instance != null) {
annonces.instance.finish();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
cat=(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView2);
ArrayAdapter adapter = new
ArrayAdapter(this,android.R.layout.simple_list_item_1,categories);
cat.setAdapter(adapter);
cat.setThreshold(1);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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);
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} 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.home) {
}
else if (id == R.id.login) {
Intent i = new Intent(this,login.class);
startActivity(i);
}
else if (id == R.id.avanced_search) {
Intent i = new Intent(this,avanced_search.class);
startActivity(i);
}
else if (id == R.id.annonces) {
Intent i = new Intent(this,avanced_search.class);
startActivity(i);
}else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void as(View view) {
EditText loc;
EditText key;
loc = (EditText)findViewById(R.id.a_loc);
key = (EditText)findViewById(R.id.a_keys);
Intent intent = new Intent(getBaseContext(), annonces.class);
intent.putExtra("ca", cat.getText().toString());
intent.putExtra("lo",loc.getText().toString());
intent.putExtra("ke", key.getText().toString());
startActivity(intent);
}
public void connect(View view) {
}
}
annonces.java
package com.example.dzweber.waslup;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.AsyncTask;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.KeyEvent;
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.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedInputStream;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.androidquery.AQuery;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import org.json.JSONObject;
public class annonces extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
public static ArrayList<annonce_item> Items = new ArrayList<annonce_item>();
public static TextView txtv;
public static String data = "";
String skey = "";
String sloc = "";
String scat = "";
String date="";
String loc="";
String cat="";
String vue="";
String titre="";
String id="";
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
public static annonces instance = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// fetchD p = new fetchD();
//p.execute();
instance = this;
skey= getIntent().getStringExtra("ke");
sloc= getIntent().getStringExtra("lo");
scat= getIntent().getStringExtra("ca");
setContentView(R.layout.activity_annonces);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
new AsyncCaller().execute();
TextView t = (TextView) findViewById(R.id.testing);
t.setText(scat);
// String generate = "https://www.waslup.pw/generation-json";
// String myurl = "https://www.waslup.pw/wp-content/uploads/wpdata.json";
// new MyAsyncTaskgetNews().execute(generate);
// new MyAsyncTaskgetNews().execute(myurl);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
@Override
public void finish() {
super.finish();
instance = null;
}
public void buclick(View view) {
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} 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.annonces, 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.home) {
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
finish();
}
else if (id == R.id.login) {
Intent i = new Intent(this,login.class);
startActivity(i);
}
else if (id == R.id.avanced_search) {
Intent i = new Intent(this,avanced_search.class);
startActivity(i);
}
else if (id == R.id.annonces) {
Intent i = new Intent(this,MainActivity.class);
startActivity(i);
}else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
class MyCustomAdapter extends BaseAdapter {
ArrayList<annonce_item> Items = new ArrayList<annonce_item>();
MyCustomAdapter(ArrayList<annonce_item> Items) {
this.Items = Items;
}
@Override
public int getCount() {
return Items.size();
}
@Override
public String getItem(int position) {
return Items.get(position).ititre;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
LayoutInflater linflater = getLayoutInflater();
View view1 = linflater.inflate(R.layout.activity_annonce_item, null);
TextView id1 = (TextView) view1.findViewById(R.id.id);
TextView date1 = (TextView) view1.findViewById(R.id.date);
TextView cat1 = (TextView) view1.findViewById(R.id.cat);
TextView loc1 = (TextView) view1.findViewById(R.id.loc);
TextView titre1 = (TextView) view1.findViewById(R.id.titre);
TextView vue1 = (TextView) view1.findViewById(R.id.vue);
date1.setText(Items.get(i).idate);
id1.setText(Items.get(i).iid);
cat1.setText(Items.get(i).icat);
loc1.setText(Items.get(i).iloc);
titre1.setText(Items.get(i).ititre);
vue1.setText(Items.get(i).ivue);
return view1;
}
}
/*
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
new AsyncCaller().execute();
}*/
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(annonces.this);
@Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("/tChargement des annonces en cours ... ");
pdLoading.show();
}
@Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("https://www.waslup.pw/wp-admin/admin-ajax.php?action=do_ajax&fn=get_posts&count=10&key="+skey+"&cat="+scat+"&loc="+sloc);
HttpURLConnection httpuc = (HttpURLConnection) url.openConnection();
InputStream inputstream = httpuc.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(inputstream));
String line ="";
while(line != null){
line = bf.readLine();
data= data + line;
}
JSONArray JA = null;
JA = new JSONArray(data);
annonces.Items.removeAll(annonces.Items);
for (int i=0 ; i<JA.length();i++){
JSONObject JO =(JSONObject) JA.get(i);
date =""+ JO.get("date");
loc =""+ JO.get("loc");
cat =""+ JO.get("Cat");
vue =""+ JO.get("vue");
titre =""+ JO.get("title");
id =""+ JO.get("Id");
annonces.Items.add(new annonce_item(id,date,loc,cat,vue,titre));
}
} catch (MalformedURLException e) {
} catch (JSONException e) {
} catch (IOException e) {
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//this method will be running on UI thread
pdLoading.dismiss();
final MyCustomAdapter myadpter = new MyCustomAdapter(Items);
ListView ls = (ListView) findViewById(R.id.listannonce);
ls.setAdapter(myadpter);
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView titre = (TextView) view.findViewById(R.id.titre);
Toast.makeText(getApplicationContext(), titre.getText(), Toast.LENGTH_LONG).show();
myadpter.notifyDataSetChanged();
TextView id2 = (TextView) view.findViewById(R.id.id);
Intent intent = new Intent(getBaseContext(), annonce_details.class);
intent.putExtra("id_from_annonces_activity", id2.getText());
startActivity(intent);
}
});
}
}
}
答案 0 :(得分:0)
我检查了您的代码并解决了您的问题。
有两件事需要讨论。
您的API根据本地化提供结果。如果我们更改前两个字段,结果将保持不变,并且Web服务仅会提取一个本地化为“ oran”的项目。但是,如果我们将本地化从“ oran”更改为“ alger”,则Web服务将显示4个结果。
这是代码中的问题。您没有在数据字符串中正确连接结果。我已经更新了您的代码,现在您在宣布Activity中的AsyncCaller代码应类似于:
这是代码
private class AsyncCaller extends AsyncTask<Void, Void, Void>
{
ProgressDialog pdLoading = new ProgressDialog(annonces.this);
@Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("/tChargement des annonces en cours ... ");
pdLoading.show();
}
@SuppressLint("NewApi")
@Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("https://www.waslup.pw/wp-admin/admin-ajax.php?action=do_ajax&fn=get_posts&count=10&key="+skey+"&cat="+scat+"&loc="+sloc);
HttpURLConnection httpuc = (HttpURLConnection) url.openConnection();
InputStream inputstream = httpuc.getInputStream();
BufferedReader bf = new BufferedReader(new InputStreamReader(inputstream));
StringBuilder total = new StringBuilder();
String line;
while ((line = bf.readLine()) != null) {
total.append(line).append('\n');
}
JSONArray JA = null;
JA = new JSONArray(total.toString());
annonces.Items.removeAll(annonces.Items);
for (int i=0 ; i<JA.length();i++){
JSONObject JO =(JSONObject) JA.get(i);
date =""+ JO.get("date");
loc =""+ JO.get("loc");
cat =""+ JO.get("Cat");
vue =""+ JO.get("vue");
titre =""+ JO.get("title");
id =""+ JO.get("Id");
annonces.Items.add(new annonce_item(id,date,loc,cat,vue,titre));
}
} catch (MalformedURLException e) {
} catch (JSONException e) {
Log.d("js_ex:",e.toString());
} catch (IOException e) {
Log.d("io_ex:",e.toString());
}
return null;
}
@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//this method will be running on UI thread
pdLoading.dismiss();
final MyCustomAdapter myadpter = new MyCustomAdapter(Items);
ListView ls = (ListView) findViewById(R.id.listannonce);
ls.setAdapter(myadpter);
ls.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView titre = (TextView) view.findViewById(R.id.titre);
Toast.makeText(getApplicationContext(), titre.getText(), Toast.LENGTH_LONG).show();
myadpter.notifyDataSetChanged();
TextView id2 = (TextView) view.findViewById(R.id.id);
Intent intent = new Intent(getBaseContext(), annonce_details.class);
intent.putExtra("id_from_annonces_activity", id2.getText());
startActivity(intent);
}
});
}
}
在这段代码中,我添加了这一部分
StringBuilder total = new StringBuilder();
String line;
while ((line = bf.readLine()) != null) {
total.append(line).append('\n');
}
JSONArray JA = null;
JA = new JSONArray(total.toString());