我使用cloudinary上传图片。
当我尝试在onCreate
中执行此操作时,它显示错误明显错误NetworkOnMainThread
。所以现在我尝试使用AsyncTask
,但现在它会产生NPE
。
09-12 23:36:18.443: E/AndroidRuntime(24715): Caused by: java.lang.NullPointerException
09-12 23:36:18.443: E/AndroidRuntime(24715): at com.example.dbms.UploadActivity$Upload.doInBackground(UploadActivity.java:51)
视图中的代码如下:
public class UploadActivity extends Activity {
private ProgressDialog dialog = null;
Cloudinary cloudinary;
JSONObject Result;
String file_path;
File file;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
Intent i = getIntent();
file_path = i.getStringExtra("file");
HashMap config = new HashMap();
config.put("cloud_name", "dbms");
config.put("api_key", "key");//I have changed the key and secret
config.put("api_secret", "secret");
Cloudinary cloudinary = new Cloudinary(config);
TextView textView = (TextView) findViewById(R.id.text5);
textView.setText(file_path);
file = new File(file_path);
}
private class Upload extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
try {
Result = cloudinary.uploader().upload(file,
Cloudinary.emptyMap());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String result) {
TextView textView = (TextView) findViewById(R.id.text5);
textView.setText("file uploaded");
}
}
public void onClick(View view) {
Upload task = new Upload();
task.execute(new String[] { "http://www.vogella.com" });
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.upload, menu);
return true;
}
}
关注的问题是:
Result = cloudinary.uploader().upload(file,
Cloudinary.emptyMap());
答案 0 :(得分:4)
您已定义cloudinary
两次 - 一次在课堂上,一次在onCreate()
。当您为onCreate()
中的cloudinary
分配值时,该类中的onCreate()
成员保持为空,因此您的应用会崩溃。最好将实例传递给AsyncTask,例如:
在Cloudinary cloudinary = new Cloudinary(config);
更改
cloudinary = new Cloudinary(config);
到
Upload
将private class Upload extends AsyncTask<String, Void, String> {
private Cloudinary mCloudinary;
public Upload( Cloudinary cloudinary ) {
super();
mCloudinary = cloudinary;
}
更改为:
doInBackground()
并在Result = cloudinary.uploader().upload(file,
Cloudinary.emptyMap());
中更改:
Result = mCloudinary.uploader().upload(file,
Cloudinary.emptyMap());
到
onClick()
最后,从
更改public void onClick(View view) {
Upload task = new Upload();
task.execute(new String[] { "http://www.vogella.com" });
}
public void onClick(View view) {
Upload task = new Upload( cloudinary );
task.execute(new String[] { "http://www.vogella.com" });
}
到
{{1}}