Java — данные MySQL не отображаются в Android RecyclerView (ошибка Logcat: не удалось загрузить модуль memtrack)

Я только начал разработку приложения для Android. Я использовал XAMPP для создания базы данных (MYSQL) и php для преобразования извлеченных данных в JSON. Однако я не смог отобразить следующий вывод JSON в Android Recyclerview, и при создании этого приложения не было сгенерировано никаких ошибок. Я также сослался на некоторые другие примеры / решения с этого сайта, но я все еще не мог решить эту проблему. Код, который я использовал ниже. Могу ли я узнать, какая часть может быть исправлена ​​или отсутствует?

herblist.php (для преобразования данных MYSQL в JSON)

<?php
include 'dbConnect.php';

// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

mysqli_set_charset($conn, 'utf8');
$sql = "SELECT * FROM herb";

$result = $conn->query($sql);

if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}

} else {
echo "No Results Found.";
}

echo $json;
$conn->close();
?>

JSON, созданный herblist.php

[{"h_name":"Basil","h_image":"http:\/\/localhost\/Herb\/Herb_image\/basil.jpg"},{"h_name":"Cilantro","h_image":"http:\/\/localhost\/Herb\/Herb_image\/cilantro.jpg"},{"h_name":"Kaffir lime leaf","h_image":"http:\/\/localhost\/Herb\/Herb_image\/kaffir_lime.jpg"},{"h_name":"Lemongrass","h_image":"http:\/\/localhost\/Herb\/Herb_image\/lemongrass.jpg"},{"h_name":"Mint","h_image":"http:\/\/localhost\/Herb\/Herb_image\/mint.jpg"},{"h_name":"Oregano","h_image":"http:\/\/localhost\/Herb\/Herb_image\/oregano.jpg"},{"h_name":"Pandan leaf","h_image":"http:\/\/localhost\/Herb\/Herb_image\/pandan.jpg"},{"h_name":"Parsley","h_image":"http:\/\/localhost\/Herb\/Herb_image\/parsley.jpg"},{"h_name":"Rosemary","h_image":"http:\/\/localhost\/Herb\/Herb_image\/rosemary.jpg"},{"h_name":"Thyme","h_image":"http:\/\/localhost\/Herb\/Herb_image\/thyme.jpg"}]

searchActivity.java (основная деятельность)

public class searchActivity extends AppCompatActivity {

List<DataAdapter> ListDataAdapter;
RecyclerView recyclerView;
String HTTP_JSON_URL = "http://localhost/Herb/herblist.php";
String Image_Name_JSON = "h_name";
String Image_URL_JSON = "h_image";
JsonArrayRequest RequestOfJSonArray ;
RequestQueue requestQueue ;
View view ;
int RecyclerViewItemPosition ;
RecyclerView.LayoutManager RecyclerViewLayoutManager;
RecyclerView.Adapter recyclerViewadapter;
ArrayList<String> ImageTitleNameArrayListForClick;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
ImageTitleNameArrayListForClick = new ArrayList<>();
ListDataAdapter = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
RecyclerViewLayoutManager = new LinearLayoutManager(this);
recyclerView.setAdapter(recyclerViewadapter);
recyclerView.setLayoutManager(RecyclerViewLayoutManager);
JSON_HTTP_CALL();

// Implementing Click Listener on RecyclerView.
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(searchActivity.this, new GestureDetector.SimpleOnGestureListener() {
@Override public boolean onSingleTapUp(MotionEvent motionEvent) {
return true;
}

});
@Override
public boolean onInterceptTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
view = Recyclerview.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if(view != null && gestureDetector.onTouchEvent(motionEvent)) {

//Getting RecyclerView Clicked Item value.
RecyclerViewItemPosition = Recyclerview.getChildAdapterPosition(view);

// Showing RecyclerView Clicked Item value using Toast.
Toast.makeText(searchActivity.this, ImageTitleNameArrayListForClick.get(RecyclerViewItemPosition), Toast.LENGTH_LONG).show();
}

return false;
}

@Override
public void onTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {

}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

}
});
}

public void JSON_HTTP_CALL(){

RequestOfJSonArray = new JsonArrayRequest(HTTP_JSON_URL,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
ParseJSonResponse(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {

}
});

requestQueue = Volley.newRequestQueue(searchActivity.this);
requestQueue.add(RequestOfJSonArray);
}

public void ParseJSonResponse(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataAdapter GetDataAdapter2 = new DataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitle(json.getString(Image_Name_JSON));

// Adding image title name in array to display on RecyclerView click event.
ImageTitleNameArrayListForClick.add(json.getString(Image_Name_JSON));

GetDataAdapter2.setImageUrl(json.getString(Image_URL_JSON));

} catch (JSONException e) {
e.printStackTrace();
}
ListDataAdapter.add(GetDataAdapter2);
}

recyclerViewadapter = new RecyclerViewAdapter(ListDataAdapter, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}

DataAdapter.java (переходная часть текста в просмотре карт)

public class DataAdapter{
public String ImageURL;
public String ImageTitle;

public String getImageUrl() {return ImageURL;}

public void setImageUrl(String ImageServerUrl) {this.ImageURL = ImageServerUrl;}

public String getImageTitle() {return ImageTitle;}

public void setImageTitle(String ImageTitleName) {this.ImageTitle = ImageTitleName;}
}

ImageAdapter.java (Адаптерная часть изображения в просмотре карт)

public class ImageAdapter {

public static ImageAdapter imageAdapter;
public Network networkOBJ ;
public RequestQueue requestQueue1;
public ImageLoader Imageloader1;
public Cache cache1 ;
public static Context context1;

LruCache<String, Bitmap> LRUCACHE = new LruCache<String, Bitmap>(30);

private ImageAdapter(Context context) {
this.context1 = context;
this.requestQueue1 = RequestQueueFunction();
Imageloader1 = new ImageLoader(requestQueue1, new ImageLoader.ImageCache() {

@Override
public Bitmap getBitmap(String URL) {
return LRUCACHE.get(URL);
}

@Override
public void putBitmap(String url, Bitmap bitmap) {
LRUCACHE.put(url, bitmap);
}
});
}

public ImageLoader getImageLoader() {
return Imageloader1;
}

public static ImageAdapter getInstance(Context SynchronizedContext) {

if (imageAdapter == null) {
imageAdapter = new ImageAdapter(SynchronizedContext);
}
return imageAdapter;
}

public RequestQueue RequestQueueFunction() {

if (requestQueue1 == null) {
cache1 = new DiskBasedCache(context1.getCacheDir());
networkOBJ = new BasicNetwork(new HurlStack());
requestQueue1 = new RequestQueue(cache1, networkOBJ);
requestQueue1.start();
}
return requestQueue1;
}
}

RecyclerViewAdapter.java

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

Context context;
List<DataAdapter> dataAdapters;
ImageLoader imageLoader;

public RecyclerViewAdapter(List<DataAdapter> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}

@Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
DataAdapter dataAdapterOBJ =  dataAdapters.get(position);
imageLoader = ImageAdapter.getInstance(context).getImageLoader();
imageLoader.get(dataAdapterOBJ.getImageUrl(),
ImageLoader.getImageListener(
Viewholder.VollyImageView,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);

Viewholder.VollyImageView.setImageUrl(dataAdapterOBJ.getImageUrl(), imageLoader);
Viewholder.ImageTitleTextView.setText(dataAdapterOBJ.getImageTitle());

}

@Override
public int getItemCount() {
return dataAdapters.size();
}

class ViewHolder extends RecyclerView.ViewHolder{

public TextView ImageTitleTextView;
public NetworkImageView VollyImageView ;

public ViewHolder(View itemView) {
super(itemView);
ImageTitleTextView = (TextView) itemView.findViewById(R.id.ImageNameTextView) ;
VollyImageView = (NetworkImageView) itemView.findViewById(R.id.VolleyImageView) ;
}
}
}

Activity_search.xml (XML-файл основного действия)

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/activity_main"android:layout_width="match_parent"android:layout_height="match_parent" >

<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview1"android:layout_width="fill_parent"android:layout_height="fill_parent" />
</RelativeLayout>

cardview.xml

<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"xmlns:card_view="http://schemas.android.com/apk/res-auto"android:id="@+id/cardview1"android:layout_width="match_parent"android:layout_height="wrap_content"card_view:cardElevation="5dp"card_view:contentPadding="5dp"card_view:cardCornerRadius="5dp"card_view:cardMaxElevation="5dp">

<RelativeLayout
android:layout_width="fill_parent"android:layout_height="wrap_content"android:background="#ECEFF1">

<com.android.volley.toolbox.NetworkImageView
android:id="@+id/VolleyImageView"android:layout_width="150dp"android:layout_height="100dp"android:src="@mipmap/ic_launcher"android:layout_marginTop="10dp"android:layout_marginBottom="10dp"/>

<TextView
android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_toEndOf="@+id/VolleyImageView"android:textSize="20sp"android:textColor="#000"android:text="JSon Image Name"android:id="@+id/ImageNameTextView"android:layout_centerVertical="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>

1

Решение

Сначала измени это

recyclerView.setHasFixedSize(true);
RecyclerViewLayoutManager = new LinearLayoutManager(this);
recyclerView.setAdapter(recyclerViewadapter);
recyclerView.setLayoutManager(RecyclerViewLayoutManager);

к

recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerViewadapter = new RecyclerViewAdapter(ListDataAdapter, this);
recyclerView.setAdapter(recyclerViewadapter);

Во-вторых, удалите эти две строки из метода JSON_HTTP_CALL ()

recyclerViewadapter = new RecyclerViewAdapter(ListDataAdapter, this);
recyclerView.setAdapter(recyclerViewadapter);

и поставить эту строку

recyclerViewadapter.notifyDataSetChanged();
0

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]