这是我的第一个应用程序,我无法得到,为什么我在应用程序中从PHP获得不同的结果。
我得到了一个recyclerView
(Endless),它获取了一个包含来自适配器的对象的数组。
class FromJsonToItem.java
从PHP脚本(连接到MySQL数据库并以JSON格式返回数据)获取数据并在ArrayList中返回
当我启动应用程序时,一切正常。我从数据库得到正确的结果,然后当我滚动视图时,应用程序加载更多数据。但是,当我尝试启动另一个活动(搜索),然后按“返回”按钮(或返回到app_bar中)返回MainActivity
时,我得到了与Mysql不同的结果。网址是一样的!
我无法找到错误,是在PHP中还是在我的应用程序中的逻辑?
MainActivity
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class MainActivity extends BaseActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "MainActivity";
String jSonResult;
private String jsonUrl = "/android/jsongetdata.php";
List<Item> mItemList = new ArrayList<>();
Context context;
int mFromLimit = 0;
private EndlessRecyclerViewScrollListener scrollListener;
private ItemRecyclerViewAdapter mItemRecyclerViewAdapter;
@Override
protected void onResume() {
Log.d(TAG, "onResume: start");
super.onResume();
int itemCount = mItemList.size();
mItemList.clear();
mItemRecyclerViewAdapter.notifyItemRangeRemoved(mFromLimit,itemCount);
getJson(jsonUrl);
Log.d(TAG, "onResume: ends");
}
@Override
protected void onPause() {
Log.d(TAG, "onPause: starts");
super.onPause();
Log.d(TAG, "onPause: ends");
}
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate: starts");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
scrollListener = new EndlessRecyclerViewScrollListener(layoutManager) {
@Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
// Triggered only when new data needs to be appended to the list
// Add whatever code is needed to append new items to the bottom of the list
Log.d(TAG, "onLoadMore: started");
Log.d(TAG, "onLoadMore: Array is ====" + String.valueOf(mItemList.size()));
mFromLimit = mFromLimit + 10;
Log.d(TAG, "onPause: ______Mfrom limit now:" + String.valueOf(mFromLimit));
loadNextDataFromApi(mFromLimit);
Log.d(TAG, "onLoadMore: ends");
}
};
recyclerView.addOnScrollListener(scrollListener);
mItemRecyclerViewAdapter = new ItemRecyclerViewAdapter(this, mItemList);
recyclerView.setAdapter(mItemRecyclerViewAdapter);
Log.d(TAG, "onCreate: SetAdapter ++++++");
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);
Log.d(TAG, "onCreate: ends");
}
public void loadNextDataFromApi(final int offset) {
Log.d(TAG, "loadNextDataFromApi: started");
// Send an API request to retrieve appropriate paginated data
// --> Send the request including an offset value (i.e `page`) as a query parameter.
String off = String.valueOf(offset);
String url = createUri("","","","","",off);
getJson(url);
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
mItemRecyclerViewAdapter.notifyItemRangeInserted(offset, mItemList.size());
}
};
Log.d(TAG, "loadNextDataFromApi: ends");
handler.post(r);
// --> Deserialize and construct new model objects from the API response
// --> Append the new data objects to the existing set of items inside the array of items
// --> Notify the adapter of the new items made with `notifyItemRangeInserted()`
}
public void getJson(String jsonUrl) {
Log.d(TAG, "getJson: starts");
FromJsonToItem fromJsonToItem = new FromJsonToItem();
fromJsonToItem.execute(jsonUrl);
try {
Log.d(TAG, "getJson: mItems size before adding" + mItemList.size());
mItemList.addAll(fromJsonToItem.get());
Log.d(TAG, "getJson: mItems size after adding" + mItemList.size());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.d(TAG, "getJson: ends");
}
private String createUri(String name, String category, String rating, String yearStart, String yearEnd, String limitFrom){
Log.d(TAG, "createUri: starts");
String uriString = jsonUrl;
if(!(name.equals(""))){
uriString = Uri.parse(uriString).buildUpon().appendQueryParameter("name", name).toString();
}
if(!(category.equals(""))){
uriString = Uri.parse(uriString).buildUpon().appendQueryParameter("category", category).toString();
}
if(!(rating.equals(""))){
uriString = Uri.parse(uriString).buildUpon().appendQueryParameter("rating", rating).toString();
}
if(!(yearStart.equals(""))){
uriString = Uri.parse(uriString).buildUpon().appendQueryParameter("yearStart", yearStart).toString();
}
if(!(yearEnd.equals(""))){
uriString = Uri.parse(uriString).buildUpon().appendQueryParameter("yearEnd", yearEnd).toString();
}
if(!(limitFrom.equals(""))){
uriString = Uri.parse(uriString).buildUpon().appendQueryParameter("limitFrom", limitFrom).toString();
}
return uriString;
}
@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;
}
if(id==R.id.action_search){
Intent intent = new Intent(this, SearchActivity.class);
startActivity(intent);
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_films) {
// Handle the camera action
} else if (id == R.id.nav_series) {
} else if (id == R.id.nav_cartoon) {
} else if (id == R.id.nav_podborki) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
我的FromJsonToItem类包含连接和解析字符串
import android.os.AsyncTask;
import android.util.Log;
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.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by moyo on 28.01.17.
*/
class FromJsonToItem extends AsyncTask<String, Void, List<Item>> {
private static final String TAG = "FromJsonToItem";
private List<Item> mItems = null;
private String mBaseUrl;
@Override
protected List<Item> doInBackground(String... params) {
String jsonUrl = params[0];
String jsonString = "";
try {
URL url = new URL(jsonUrl);
mBaseUrl = jsonUrl;
Log.d(TAG, "doInBackground: opening connection");
Log.d(TAG, "doInBackground: NOW URL IS:" + mBaseUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while((jsonString=bufferedReader.readLine())!=null){
stringBuilder.append(jsonString+"\n");
}
jsonString = stringBuilder.toString();
Log.d(TAG, "doInBackground: json get next string: " + jsonString);
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
Log.d(TAG, "doInBackground: connection closed");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Generate JSON object from String
mItems = new ArrayList<>();
try {
JSONObject jsonData = new JSONObject(jsonString);
JSONArray itemsArray = jsonData.getJSONArray("server_response");
HashMap<String, String> fieldsMap = new HashMap<>();
for(int i = 0; i<itemsArray.length(); i++){
JSONObject jsonFilm = itemsArray.getJSONObject(i);
String title = jsonFilm.getString("title");
int id = jsonFilm.getInt("id");
String shortStory = jsonFilm.getString("short_story");
String[] categories = jsonFilm.getString("category").split(",");
int[] intCategories = new int[categories.length];
for(int j = 0; j < categories.length; j++)
{
intCategories[j] = Integer.parseInt(categories[j]);
}
String xFields = jsonFilm.getString("xfields");
xFields = xFields.replaceAll("\\\\","");
// Log.d(TAG, "doInBackground: xfields: " + xFields);
String[] splitXfields = xFields.split("\\|\\|");
//fill the MAP with key,value from the xfields
for(int j = 0; j<splitXfields.length; j++ ){
String temp = splitXfields[j];
String[] tempArray = temp.split("\\|");
if(tempArray.length==2){
fieldsMap.put(tempArray[0],tempArray[1]);
}
}
// Log.d(TAG, "doInBackground: tempArray:" + fieldsMap.toString());
//When map is filed, starting creating Item objects
String age = "";
String poster = "";
String original = "";
String trailer = "";
String god = "";
String rol = "";
String re = "";
String country = "";
String company = "";
String length = "";
String rating = "";
String imdb = "";
String name = "";
String torrents = "";
String audio = "";
String video = "";
String format = "";
String size = "";
String torrent = "";
for (Map.Entry<String, String> entry : fieldsMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
switch(key){
case "poster":
poster = value;
break;
case "original":
original = value;
break;
case "treller":
trailer = value;
break;
case "god":
god = value;
break;
case "rol":
rol = value;
break;
case "re":
re = value;
break;
case "country":
country = value;
break;
case "comp":
company = value;
break;
case "prod":
length = value;
break;
case "rating":
rating = value;
break;
case "name":
name = value;
break;
case "age":
age = value;
break;
case "torrents":
torrents = value;
break;
case "audio":
audio = value;
break;
case "video":
video = value;
break;
case "format":
format = value;
break;
case "size":
size = value;
break;
case "torrent":
torrent = value;
break;
case "imdb":
imdb = value;
break;
}
}
shortStory = android.text.Html.fromHtml(shortStory).toString();
shortStory = shortStory.replaceAll("\\\\","");
Item item = new Item(age,audio,intCategories,company,country,format,god,id,imdb,length,name,original,poster,
rating,re,rol,shortStory,size,title,torrent,torrents,trailer,video);
//Log.d(TAG, "doInBackground: Item" + item.toString());
// Log.d(TAG, "doInBackground: =================");
mItems.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
}
return mItems;
}
@Override
protected void onPostExecute(List<Item> items) {
}
}
用于从DB获取数据的PHP文件 我传递了url中的参数(如果是),这些参数在
中生成MainActivity.createUri
<?php
$host="localhost";
$database="*****";
$username="*****";
$password="****";
$name;
$category;
$rating;
$yearStart;
$yearEnd = 2017;
$limitFrom = 0;
if (isset($_GET['name'])) {
$name = $_GET['name'];
$name .="%";
}
if (isset($_GET['category'])) {
$category = $_GET['category'];
$category .="%";
}
if (isset($_GET['rating'])) {
$rating = $_GET['rating'];
}
if (isset($_GET['yearStart'])) {
$yearStart = $_GET['yearStart'];
}
if (isset($_GET['yearEnd'])) {
$yearEnd = $_GET['yearEnd'];
}
if (isset($_GET['limitFrom'])) {
$limitFrom = $_GET['limitFrom'];
}
$sqlYearStart = " xfields like '%dates|";
$sqlYearStart .=$yearStart;
$sqlYearStart .= "%'";
$sqlName = " and title like '%";
$sqlName .= $name;
$sqlName .= "'";
$sqlCategory = " and category like '%";
$sqlCategory .= $category;
$sqlCategory .= "'";
$sqlRating = " and (xfields like '%rating|";
$sqlRating .= $rating;
$sqlRating .= "%'";
$sqlRating .= " or xfields like '%imdb|";
$sqlRating .= $rating;
$sqlRating .= "%')";
$sql= "select dle_post.id,dle_post.title,dle_post.short_story,dle_post.xfields,dle_post.category from dle_post where";
$sql .= $sqlYearStart;
$sql .= $sqlName;
$sql .= $sqlCategory;
$sql .= $sqlRating;
$sql .= " order by dle_post.id DESC limit ";
$sql .= $limitFrom;
$sql .= ", 10;";
$con =mysqli_connect($host,$username,$password,$database);
mysqli_set_charset($con,"utf8");
$result= mysqli_query($con,$sql);
$response= array();
while($row=mysqli_fetch_array($result))
{
array_push($response,array("id"=>$row[0],"title"=>$row[1],"short_story"=>$row[2],"xfields"=>$row[3],"category"=>$row[4]));
}
$json = json_encode(array("server_response"=>$response), JSON_UNESCAPED_UNICODE);
echo $json;
mysqli_close($con);
?>
如果有帮助,我可以添加一条logcat消息。需要焕然一新,因为我处于僵局
先谢谢。