Ошибка при отображении изображений из MySQL в представлении переработчика с помощью Android Studio

Я хотел бы отображать изображения из MySQL в RecyclerView. Я сохранил путь к базе данных. Приложение будет извлекать изображения, получая URL-адрес изображений из базы данных. Приложение зависало при запуске. У меня действительно нет идей, где пойти не так.
Я получаю эту ошибку при запуске приложения. Мне нужна помощь и руководство. Пожалуйста, помогите мне….

12-23 08:31:04.822 26595-26595/bhouse.travellist E/AndroidRuntime: FATAL EXCEPTION: main
12-23 08:31:04.822 26595-26595/bhouse.travellist E/AndroidRuntime: Process: bhouse.travellist, PID: 26595
12-23 08:31:04.822 26595-26595/bhouse.travellist E/AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
12-23 08:31:04.822 26595-26595/bhouse.travellist E/AndroidRuntime:     at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
12-23 08:31:04.822 26595-26595/bhouse.travellist E/AndroidRuntime:     at org.json.JSONTokener.nextValue(JSONTokener.java:94)
12-23 08:31:04.822 26595-26595/bhouse.travellist E/AndroidRuntime:     at org.json.JSONObject.<init>(JSONObject.java:156)
12-23 08:31:04.822 26595-26595/bhouse.travellist E/AndroidRuntime:     at org.json.JSONObject.<init>(JSONObject.java:173)
12-23 08:31:04.822 26595-26595/bhouse.travellist E/AndroidRuntime:     at bhouse.travellist.MainActivity.showList(MainActivity.java:66)
12-23 08:31:04.822 26595-26595/bhouse.travellist E/AndroidRuntime:     at bhouse.travellist.MainActivity$1GetURLs.onPostExecute(MainActivity.java:106)
12-23 08:31:04.822 26595-26595/bhouse.travellist E/AndroidRuntime:     at bhouse.travellist.MainActivity$1GetURLs.onPostExecute(MainActivity.java:92)
12-23 08:31:04.822 26595-26595/bhouse.travellist E/AndroidRuntime:     at android.os.AsyncTask.finish(AsyncTask.java:632)
12-23 08:31:04.822 26595-26595/bhouse.travellist E/AndroidRuntime:     at android.os.AsyncTask.access$600(AsyncTask.java:177)
12-23 08:31:04.822 26595-26595/bhouse.travellist E/AndroidRuntime:     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
12-23 08:31:04.822 26595-26595/bhouse.travellist E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:102)
12-23 08:31:04.822 26595-26595/bhouse.travellist E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:135)
12-23 08:31:04.822 26595-26595/bhouse.travellist E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5221)
12-23 08:31:04.822 26595-26595/bhouse.travellist E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
12-23 08:31:04.822 26595-26595/bhouse.travellist E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:372)
12-23 08:31:04.822 26595-26595/bhouse.travellist E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
12-23 08:31:04.822 26595-26595/bhouse.travellist E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

MainActivity.java

public class MainActivity extends Activity {

private Toolbar toolbar;

private RecyclerView mRecyclerView;
private StaggeredGridLayoutManager mStaggeredLayoutManager;
private TravelListAdapter mAdapter;
private boolean isListView;
private Menu menu;
String myJSON;
JSONArray images = null;
private static final String TAG_RESULTS="result";
private final ArrayList<images> pairs = new ArrayList<images>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

toolbar = (Toolbar) findViewById(R.id.toolbar);
setUpActionBar();

mStaggeredLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);

mRecyclerView = (RecyclerView) findViewById(R.id.list);
mRecyclerView.setLayoutManager(mStaggeredLayoutManager);

mRecyclerView.setHasFixedSize(true); //Data size is fixed - improves performance

getData();
}
protected void showList(String json){
try {
JSONObject jsonObj = new JSONObject(json);
images = jsonObj.getJSONArray(TAG_RESULTS);

for(int i=0;i<images.length();i++){
JSONObject c = images.getJSONObject(i);

String name = c.getString("name");
String url= c.getString("url");

pairs.add(new images( name , url ));


}

mAdapter = new TravelListAdapter(MainActivity.this,pairs);
mRecyclerView.setAdapter(mAdapter);

} catch (JSONException e) {
e.printStackTrace();
}

}

private void getData() {
class GetURLs extends AsyncTask<String,Void,String> {
ProgressDialog loading;

@Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this,"Loading...","Please Wait...",true,true);
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
loading.dismiss();
showList(result);
}

@Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://192.168.1.10/VideoUpload/getAllImages.php");

// 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;
}
}
GetURLs gu = new GetURLs();
gu.execute();
}

private void setUpActionBar() {
if (toolbar != null) {
setActionBar(toolbar);
getActionBar().setDisplayHomeAsUpEnabled(false);
getActionBar().setDisplayShowTitleEnabled(true);
getActionBar().setElevation(7);
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
this.menu = menu;
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_toggle) {
toggle();
return true;
}
return super.onOptionsItemSelected(item);
}

private void toggle() {
MenuItem item = menu.findItem(R.id.action_toggle);
if (isListView) {
mStaggeredLayoutManager.setSpanCount(2);
item.setIcon(R.drawable.ic_action_list);
item.setTitle("Show as list");
isListView = false;
} else {
mStaggeredLayoutManager.setSpanCount(1);
item.setIcon(R.drawable.ic_action_grid);
item.setTitle("Show as grid");
isListView = true;
}
}
}

TravelListAdapter.java

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

Context mContext;
OnItemClickListener mItemClickListener;

private ArrayList<images> pairs;

public TravelListAdapter(Context context ,ArrayList<images> pairs ) {
this.mContext = context;
this.pairs = pairs;
}

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

@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {

holder.placeName.setText(pairs.get(position).name);
Picasso.with(mContext).
load(pairs.get(position).url).
into(holder.placeImage);

Bitmap photo =getBitmapFromURL(pairs.get(position).url);

Palette.generateAsync(photo, new Palette.PaletteAsyncListener() {
public void onGenerated(Palette palette) {
int mutedLight = palette.getMutedColor(mContext.getResources().getColor(android.R.color.black));
holder.placeNameHolder.setBackgroundColor(mutedLight);
}
});
}

public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
@Override
public int getItemCount() {
return pairs.size();
}

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public LinearLayout placeHolder;
public LinearLayout placeNameHolder;
public TextView placeName;
public ImageView placeImage;

public ViewHolder(View itemView) {
super(itemView);
placeHolder = (LinearLayout) itemView.findViewById(R.id.mainHolder);
placeName = (TextView) itemView.findViewById(R.id.placeName);
placeNameHolder = (LinearLayout) itemView.findViewById(R.id.placeNameHolder);
placeImage = (ImageView) itemView.findViewById(R.id.placeImage);
placeHolder.setOnClickListener(this);
}

@Override
public void onClick(View v) {
if (mItemClickListener != null) {
mItemClickListener.onItemClick(itemView, getPosition());
}
}
}

public interface OnItemClickListener {
void onItemClick(View view, int position);
}

public void setOnItemClickListener(final OnItemClickListener mItemClickListener) {
this.mItemClickListener = mItemClickListener;
}

}

getAllImages.php

<?php
require_once('dbConnect.php');

$sql = "select * from uploads where id=52";

$res = mysqli_query($con,$sql);

$result = array();

while($row = mysqli_fetch_array($res)){
array_push($result,array(
'url'=>$row['image'],
'name'=>$row['name']
));
}

echo json_encode(array("result"=>$result));

mysqli_close($con);
?>

1

Решение

Задача ещё не решена.

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

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

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector